Neo4j Cypher: copy relationships and delete node

风流意气都作罢 提交于 2019-12-31 04:09:10

问题


I'm trying to copy all inward relationships of a node (n) to another node (m) (both of witch I know the ids) before deleting (n), but I couldn't come up with the code. The relationships may or may not exist.

Anybody snippet?


回答1:


You wont be able to create a relationshiptype dynamically from inside a collection of relationships.

Suppose even if we collect all the incoming relationships as below

START n=node(id1) MATCH n<-[r]-() WITH collect(r) as rels ...

You would be able to iterate over the collection rels but WOULD NOT be able to do below

CREATE (n)-[rels[i]]->(m)

So assuming if all incoming relationships are of same type say 'foo'. Then you could do the following.

START n=node(id1),m=node(id2) 
MATCH n<-[r:foo]-(p) 
WITH collect(p) as endNodes,m
FOREACH(i in range(0,length(endNodes)-1) | foreach(a in [endNodes[i]] | 
 create m<-[:foo]-a 
))

In case if your relationshipTypes are different, then you can refer this workaround technique :here. You can query from the console, download all startnode , endnode, relationshiptype info as csv into excel sheet. And then run cypher script to run from it.

Other way is you can query using java api for neo4j and then store all the relationships and nodes , frame your queries accordingly and fire back again.




回答2:


assuming all incoming relationships are of same type say 'foo'. Then you could do the shorter following query:

START n=node(id1),m=node(id2) 
MATCH n<-[r:foo]-(p) 
WITH collect(p) as endNodes,m
FOREACH(mm in endNodes | CREATE m-[:foo]->mm)

Which avoids the double foreach



来源:https://stackoverflow.com/questions/21634936/neo4j-cypher-copy-relationships-and-delete-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!