0
votes

I have a database with nodes like

(u : Update)-[:HAS_COMMENT]->(latest_comment:Comment)-[:NEXT]->(c1: Comment)->(c2: Comment) 

And so on.. Each Comment node has a relation with User node

(c : Comment)<-[:HAS_COMMENTED]-(u : User).

Now I have to delete the update node so with this all the comment nodes should be deleted and relation between User and Comment should also be deleted.

The solution that came to my mind is to traverse from last Comment node and start deleting relation with User node and delete Comment node and "NEXT" relation with the previous comment node. I am facing the problem to write such query.

Can someone help me with this?

1

1 Answers

1
votes

Use a variable length path in an OPTIONAL MATCH statement to match on all Comments in the path (chained together with :NEXT relationships) then use DETACH DELETE to delete the nodes and relationships:

MATCH (u:Update {name: "UpdateToDelete"})-[:HAS_COMMENT]->(c:Comment)
OPTIONAL MATCH (c)-[:NEXT*]->(r:Comment)
DETACH DELETE u,c,r

DETACH DELETE will remove nodes and any relationships connected to the nodes being deleted.

Here is a Neo4j console to test.

Edit

The DETACH DELETE statement was added in Neo4j version 2.3. To accomplish this without using DETACH DELETE try this query:

MATCH (u:Update {name: "UpdateToDelete"})-[hc:HAS_COMMENT]->(c:Comment) 
MATCH (c)-[n:NEXT*0..]->(r:Comment), (r)<-[h:HAS_COMMENTED]-(:User) 
FOREACH (x IN n | DELETE x) 
DELETE r,u,hc,c,h

The key difference is that without using DETACH DELETE we have to match on each relationship that connects a given node and delete those relationships when we delete the node. Since we have a variable length path (Comments connected by an arbitrary number of NEXT relationships) we can use the FOREACH function to iterate through the collection of NEXT relationships and delete them as we delete the Comment node(s).