合并neo4j中的现有记录,删除重复项,保持可选关系

时间:2015-08-28 15:44:53

标签: graph neo4j cypher

这类似于Merge existing records in neo4j, remove duplicates, keep relationships,除了我要合并的节点有我想保留的0-2个关系。

拍摄生成的图表:

create (:Person {name:"Bob"})-[:RELATED_TO]->(:Person {name:"Jane"})-[:FRIENDS_WITH]->(:Person {name:"Tim"})<-[:FRIENDS_WITH]-(:Person {name:"Jane"}),
(:Person {name:"Sally"})-[:RELATED_TO]->(:Person {name:"Jane"})

我想合并重复的Jane节点,保留RELATED_TO和FRIENDS_WITH关系,删除重复项。

从另一个问题我可以得到:

match (p:Person {name:"Jane"})
with p.name as name, collect(p) as ps, count(*) as pcount
where pcount > 1
with head(ps) as first, tail(ps) as rest
unwind rest as to_delete
return to_delete

但我似乎无法让匹配和/或可选匹配正确合并。我尝试链接可选匹配并在一个语句中执行合并,neo4j给了我一个Statement.ExecutionFailure,没有其他消息。我尝试将合并分解为每个匹配,最后得到“其他节点为空”。想法?

1 个答案:

答案 0 :(得分:4)

以下查询正在运行。在旁注中,对于这种重构,我希望有可能设置一个动态变量的关系类型:

MATCH (n:Person { name:"Jane" })
WITH collect(n) AS janes
WITH head(janes) AS superJane, tail(janes) AS badJanes 
UNWIND badJanes AS badGirl
OPTIONAL MATCH (badGirl)-[r:FRIENDS_WITH]->(other)
OPTIONAL MATCH (badGirl)<-[r2:RELATED_TO]-(other2)
DELETE r, r2, badGirl
WITH superJane, collect(other) AS friends, collect(other2) AS related
FOREACH (x IN friends | MERGE (superJane)-[:FRIENDS_WITH]->(x))
FOREACH (x IN related | MERGE (x)-[:RELATED_TO]->(superJane))

结果:

enter image description here