Delete the previous node and relationship and point it to the current node with same relationship

Viewed 81

I'm trying to form a relationship b/w parent and child.

MERGE (c:Child{name:'CA'})
MERGE (p:Parent{name:'Parent'})

For creating a relationship,

MERGE (p)-[:parent_of]->(c)

This queries are written in a separate java function named createParentChildRelationship. Whenever I try to call this function with a same Parent name with a different child name passing a parameter to the function, it forms a new relationship . But I need only the current child node to point the parent node, by deleting the previous child nodes and it's relationship with the parent. So I tried this way of approaching it,

MERGE (c:Child{name:'CA'})
MERGE (p:Parent{name:'Parent'})
MATCH (c)-[r:parent_of]-(p) DELETE r, c, p
CREATE (p)-[:parent_of]->(c) 

But it shows me 1 property is set but relationship isn't created

2 Answers

Two problems with your query:

  1. You're deleting the parent, the child, and the relationship. You can't create a new relationship to a new child if you just deleted the parent. Also you're deleting the child you just created, not the current child of the parent, so that needs fixing too.

  2. If a MATCH fails, then there are no rows to execute upon, and nothing else will happen in the query. You may want an OPTIONAL MATCH instead, or maybe a pattern comprehension.

You could give this a try instead:

MERGE (p:Parent {name:'Parent'})
WITH p, [(p)-[:parent_of]->(existing) | existing] as existingChildren
FOREACH (child IN existingChildren | DETACH DELETE child)
MERGE (c:Child {name:'CA'})
CREATE (p)-[:parent_of]->(c)

Try this, it works on my neo4j desktop;

  1. Find that relationship between CA and parent (OPTIONAL because it will continue the query if there is no match found)
  2. Delete the relationship
  3. Find that parent and create if not found (MERGE)
  4. Using the child and parent nodes, create a new relationship
OPTIONAL MATCH (c:Child)-[r:parent_of]-(:Parent{name:'Parent'})
DELETE r
MERGE (p2:Parent{name:'Parent'})
MERGE (p2)-[r2:parent_of]->(c2:Child{name:'CA'})
RETURN c2, r2, p2

You cannot delete c and p since it is still part of the query during create.

Related