Sovos
Sovos

Reputation: 3390

Neo4j Cypher: copy relationships and delete node

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?

Upvotes: 1

Views: 3091

Answers (2)

colin
colin

Reputation: 81

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

Upvotes: 1

Sumeet Sharma
Sumeet Sharma

Reputation: 2583

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.

Upvotes: 2

Related Questions