neo4j中的CREATE UNIQUE产生重复的节点 [英] CREATE UNIQUE in neo4j produces duplicate nodes
问题描述
根据 neo4j文档:
CREATE UNIQUE位于MATCH和CREATE之间-它将匹配 它可以做什么,并创造缺失的东西. CREATE UNIQUE将永远 尽可能少地改变图表—如果可以使用 现有图形,它将.
CREATE UNIQUE is in the middle of MATCH and CREATE — it will match what it can, and create what is missing. CREATE UNIQUE will always make the least change possible to the graph — if it can use parts of the existing graph, it will.
这听起来不错,但是CREATE UNIQUE
似乎并没有遵循最少可能的更改"规则.例如,这里有一些Cypher可以创建两个人:
This sounds great, but CREATE UNIQUE
doesn't seem to follow the 'least possible change' rule. e.g., here is some Cypher to create two people:
CREATE (n:Person {name: 'Alice'})
CREATE (n:Person {name: 'Bob'})
CREATE INDEX ON :Person(name)
和这两个CREATE UNIQUE
语句,用于在这些人之间建立关系.由于两个人都已经存在于图中,因此仅应重新创建关系:
and here's two CREATE UNIQUE
statements, to create a relationship between those people. Since both people already exist in the graph, only the relationships should be newly created:
MATCH (a:Person {name: 'Alice'})
CREATE UNIQUE (a)-[:knows]->(b:Person {name: 'Bob'})
RETURN a
MATCH (a:Person {name: 'Alice'})
CREATE UNIQUE (a)<-[:knows]-(b:Person {name: 'Bob'})
RETURN a
此后,图形应类似于
(Alice)<---KNOWS--->(Bob).
但是当您运行MATCH查询时:
But when you run a MATCH query:
MATCH (a:Person)
RETURN a
现在该图看起来像
(Bob)
(Bob)--KNOWS-->(Alice)--KNOWS-->(Bob);
已经创建了两个额外的鲍勃.
two extra Bobs have been created.
我仔细查看了其他Cypher命令,但似乎都不适合本用例:如果存在B,则在现有节点A和现有节点B之间创建链接,否则在现有节点A和a之间创建链接.新创建的节点B.如何在Cypher框架中最好地解决此问题?
I looked a bit through the other Cypher commands, but none of them seem intended for this use case: create a link between existing node A and existing node B if B exists, and otherwise create a link between existing node A and a newly created node B. How can this problem best be solved within the Cypher framework?
推荐答案
此查询应执行您想要的操作(如果您始终希望最终在两个节点之间使用单个knows
关系)
This query should do what you want (if you always want to end up with a single knows
relationship between the 2 nodes):
MATCH (a:Person {name: 'Alice'})
MERGE (b:Person {name: 'Bob'})
MERGE (a)-[:knows]->(b)
RETURN a;
这篇关于neo4j中的CREATE UNIQUE产生重复的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!