cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Move all relationships from one node to another

rlukas
Node Link

This seems simple and I am sure it is, but everything is simple if you know how and.. well.. sigh.
lets say I have this;

merge (N1:Node1{name:"N1"})-[r:pointsTo]->(X1:NodeX{name:"X1"})
create (X2:NodeX{name:"X2"})
merge (N1)-[:pointsTo]->(X2)
create (X3:NodeX{name:"X3"})
merge (N1)-[:pointsTo]->(X3)
with N1, X2, X3
match (n:NodeX)-[r]->(x) return n, r, x

now take all the pointsTo relationships and attach them to a new node, say
match (n:NodeX)-[r]-() return r gives me all the relationships
now what.. ?? i need to take those r's and assign them to a new node and detach them from the old node...

sorry for the stupid question.. and thanks for showing me the light out of my tunnel of misery.. hopefully i can do something for you guys 🙂

5 REPLIES 5

You could use apoc.refactor, but this would effectively be the same:

Note, directionality is sensitive here. If you want to move all (both in and out) rels from :NodeX, you'll have to do this twice. (once for each direction)

MATCH (n:NodeX)-[r]->(tgt)
MERGE (x:NewNode)
CREATE (n)-[rNew :pointsTo]->(tgt)
SET rNew = r
DELETE r

If you want to do this without respect to the Relationship labels, and keep those labels, you'll have to use apoc.refactor.

yes.. thanks.. I should have mentioned that I need something that is not tied to a specific relationship name.. See this could be for any node or any type and so, the relationship link could be named anything and there will probably be many different types of relationship links. I think i have to (should) dig into the apoc.refactor mechanism.. I started looking at that a little while ago.. .. 🙂 thanks tony.. thanks man. you have a good weekend sir..

...that was an interesting stream of consciousness. ^_^

Here ya go:

MATCH (n:NodeX)
MERGE (x:NewNode)
WITH n, x
MATCH (n)-[r]->()
CALL apoc.refactor.to(x,r) YEILD output RETURN output
;

MATCH (n:NodeX)
MERGE (x:NewNode)
WITH n, x
MATCH (n)<-[r]-()
CALL apoc.refactor.from(x,r) YEILD output RETURN output
;

What if we have multiple relatioships?

rlukas
Node Link

excellent.. thanks man.. I thought that there was a good way to do this.. thanks man for helping me out.. the rest of the day I am dedicating to More Study Time.. This is great stuff.. see you Captain