7

Assume I have this model in neo4j:

          (n2) -> (n3)-> (n9)
           /\
           |
   (n4)<-(n1)->(n5)->(n6)
    |            |
    \/           \/ 
    (n7)         (n8)

I need a cypher to change relationship between (n1) and (n2) to (n1) and (n6), like this:

                     (n2) -> (n3)-> (n9)
                      /\
                      |
   (n4)<-(n1)->(n5)->(n6)
    |            |
    \/           \/ 
    (n7)         (n8)
Arash Mousavi
  • 2,110
  • 4
  • 25
  • 47

3 Answers3

8

For those without APOC, Here is how to copy the relationship

MATCH (n1)-[r1:foo]->(n2),(n6)
WHERE n1.id = 1 AND n2.id = 2 and n6.id = 6
CREATE (n2)-[r2:foo]->(n6)
SET r2=r1
DELETE r1
Tezra
  • 8,463
  • 3
  • 31
  • 68
4

If you have APOC Procedures installed, you can use a graph refactoring procedure to change the end point of a relationship. You'll need a match query to get the relationship, and the new start node, then use:

call apoc.refactor.from(rel, newStartNode)
InverseFalcon
  • 29,576
  • 4
  • 38
  • 51
  • apoc.refactor.to(rel, newEndNode) comes in handy as well. – TomEberhard Nov 02 '21 at 06:36
  • Note that the proc does not modify the existing relationship, since that isn't possible. Instead this procedure is shorthand for creating a new relationship, copying over the properties, and deleting the old relationship. – InverseFalcon Nov 03 '21 at 11:46
2

As mentioned in a StackOverflow question about changing endpoints of a relationship, Neo4j has no method for changing the start or end nodes of a relationship - see the Javadoc for Relationship.

But you could do this with a Cypher query that copied the properties of the first relationship to a new relationship using the properties() function, and then deleted the first relationship.

However, the ID would change in the process, and Cypher's SET clause doesn't appear to allow you to manually set the ID for something.

Community
  • 1
  • 1
bouteillebleu
  • 2,456
  • 23
  • 32