Search code examples
neo4jcypher

Swapping specific properties of two nodes including relationships in Neo4j


I'm trying to swap multiple properties and all relationships between two nodes in Neo4j. For example-

Node 1 -> {id='id1',name:'ABC',city='London'} belongs to A
Node 2 -> {id='ID1',name:'PQR',city='Paris'} belongs to B

After Query Execution, the result should be-

Node 1 -> {id='id1',name:'PQR',city='Paris'} will belong to B
Node 2 -> {id='ID1',name:'ABC',city='London'} will belong to A

Note: id is case-sensitive hence two nodes with similar text are present. We don't want to swap id property.

Tried doing it with set properties(node) and Temp node like-

MATCH
  (node1 {id: 'id1'}),
  (node2 {id: 'ID1'})
CREATE (Temp:Student{properties(node1)}) 
AND SET node1.name = node2.name, node1.city = node2.city
AND SET node2.name = Temp.name, node2.city = Temp.city
AND DELETE Temp 
RETURN node1,node2

Getting following error

Invalid input '(': expected "}" (line 4, column 33 (offset: 99))
"CREATE (Temp:Student{properties(node1)})"

Wanted to know if it's possible without creating a Temp node.

Thank you.


Solution

  • You should use the WITH clause to store temporary values. Assuming both nodes have the Student label, this query should work:

    MATCH
      (n1:Student {id: 'id1'}),
      (n2:Student {id: 'ID1'})
    WITH n1, n2, n1.name AS name1, n1.city AS city1
    SET
      n1.name = n2.name, n1.city = n2.city,
      n2.name = name1, n2.city = city1
    RETURN n1, n2