本文介绍了合并neo4j中的现有记录,删除重复项,保持可选关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于合并neo4j中的现有记录,删除重复项,保留关系,除了我要合并的节点具有我要保留的0-2关系.

This is similar to Merge existing records in neo4j, remove duplicates, keep relationships, except that the nodes I want to merge have 0-2 relationships I want to keep.

获取由以下人员生成的图形:

Take the graph generated by:

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关系,删除重复项.

I want to merge the duplicate Jane nodes, preserving the RELATED_TO and FRIENDS_WITH relationships, removing the duplicates.

从另一个问题我可以得出以下结论:

From the other question I can get as far as:

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而没有其他消息.我尝试将合并合并到每个匹配项中,并以其他节点为空"结束.有想法吗?

But I can't seem to get the matches and/or optional matches correct for merging. I tried chaining optional matches and doing the merge in one statement and neo4j gives me a Statement.ExecutionFailure with no additional message. I tried breaking out the merges into each match and ended up with "other node is null". Thoughts?

推荐答案

以下查询正在运行.附带一提,对于这种重构,我很希望有一天可以设置带有动态变量的关系类型:

The following query is working. On a side note, for this kind of refactoring I would love the day when it would be possible to set a relationship type with a dynamic variable :

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))

结果:

这篇关于合并neo4j中的现有记录,删除重复项,保持可选关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:27