1

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?

Sovos
  • 3,330
  • 7
  • 25
  • 36

2 Answers2

2

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.

Sumeet Sharma
  • 2,573
  • 1
  • 12
  • 24
  • This is neat thanks! Still the DELETE problem remains, ie: if I try to run the DELETE query afterwards but no relationships have been found before, won't the query fail? – Sovos Feb 08 '14 at 20:25
  • Neo4j api doc says no relationship is left hanging . So as soon as you delete a node all relationships corresponding to it should get deleted too – Sumeet Sharma Feb 09 '14 at 08:09
  • When I tried to delete a node with relationships and it gave me an error. I must delete both nodes and relationships for it to succeed. Presuming that we know the relationship type, do you see any way to do it in one query? – Sovos Feb 09 '14 at 21:14
  • start n= node(id1) MATCH n<-[r]-() delete n,r – Sumeet Sharma Feb 10 '14 at 05:45
1

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

colin
  • 81
  • 2
  • 7