2015-08-28 62 views
1

這與Merge existing records in neo4j, remove duplicates, keep relationships類似,只是我想要合併的節點具有0-2的關係。合併neo4j中的現有記錄,刪除重複項,保留可選關係

取所產生的圖形:

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

我想合併重複簡節點,保留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,沒有額外的消息。我試圖打破每場比賽的合併,並以「其他節點爲空」結束。思考?

回答

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

+0

正是曾擔任我想了。謝謝! – David

相關問題