我无法捕获 ConstraintError 异常。
当我运行这个时:
try:
tx.run('MERGE (:Person {{name:"{name}",country:"{country}"}})'.format(name=name,country=country))
except ConstraintViolation:
pass
异常仍然存在。
我试过了
from neo4j.v1 import exceptions
还有 ConstraintError 和 ConstraintViolation。
但是,无论我 try catch ConstraintError 还是 ConstraintViolation,我都会收到此错误:
ConstraintError: Node(5314) already exists with label `Person` and property `name` = 'SomeThing'
我该如何正确处理这个问题?
请您参考如下方法:
假设这个节点已经存在(为清楚起见,我使用字符串文字而不是参数):
(:Person {name: "SomeThing", country: "Canada"})
然后您提出此请求:
MERGE (:Person {name: "SomeThing", country: "USA"})
您会得到一个 ConstraintError,因为这样的节点尚不存在(具有两个属性值),而且您也无法创建该节点(因为唯一性约束)。
可能的修复
如果你想强制
country值为“USA”,无论如何,这应该避免ConstraintError:MERGE (p:Person {name: "SomeThing"}) SET p.country = "USA";或者,如果您只想在具有该
name值的节点尚不存在时设置country值,那么这应该可行:MERGE (p:Person {name: "SomeThing"}) ON CREATE SET p.country = "USA";或者,如果您只想在具有该
name值的节点已经存在时设置country值,那么这应该可行:MERGE (p:Person {name: "SomeThing"}) ON MATCH SET p.country = "USA";
