3
votes

I have a tree like node structure in my Neo4j DB. When I delete particular node I want to delete all child nodes and relationships related to that node. Consider node structure generated by below query,

merge (p1:Person{nic:'22222v'})-[r1:R1]->(p2:Person{nic:'33333v'}) 
merge(p1)-[r2:R2]->(p3:Person{nic:'44444v'}) 
merge(p2)-[r3:R3]->(p3) 
merge (p3)-[r4:R4]->(p4:Person{nic:'55555v'}) 
merge(p4)-[r5:R5]->(p5:Person{nic:'66666v'}) 
return r1,r2,r3,r4,r5

If I input node(nic:44444v) it should delete node(nic:44444v),node(nic:55555v),node(nic:66666v ), relationship(r2),relationship(r3),relationship(r4) and relationship(r5)

1

1 Answers

7
votes

You can use multiple depth relationships and delete the nodes :

MATCH (n:Person {nic:'44444v'})-[*0..]->(x)
DETACH DELETE x

The 0.. depth definition will embed the n identifier in the x nodes and thus will handle the case where the person doesn't have children nodes.

Alternative syntax for oldier neo4j versions :

MATCH (n:Person {nic:'44444v'})-[*0..]->(x) 
OPTIONAL MATCH (x)-[r]-() 
DELETE r, x