Matthias
Matthias

Reputation: 254

Cypher delete a node and all related nodes if they don't have a further relations

To keep my database clean from orphaned nodes, I want to delete a Node - identified by a given property value - and every related Node that does not have any other related nodes.

Is that possible? Currently I'm doing this:

MATCH (poi:PointOfInterest)-[r]-(allRelatedNodes) 
WHERE poi.id="X007" 
DETACH DELETE poi, r, allRelatedNodes;

But that deletes all related Nodes including the ones that would be connected to other Nodes if they weren't deleted.

Is there a way to delete a Node and all related Nodes that don't have relations to other Nodes?


Edit by the author:

The marked answer is correct. I finally solved my problem with

MATCH (poi:Node)-[r*0..1]-(allRelatedNodes) 
WHERE poi.name = "A"
AND size((allRelatedNodes)--()) < 2    
DETACH DELETE poi, allRelatedNodes;

Upvotes: 2

Views: 1577

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

If you make the allRelatedNodes match optional and ensure allRelatedNodes only have a single relationship to poi then you should be able to delete only the ones attached to X007 if they exist. Also, you don't need to specify r in the delete statement as DETACH takes care of that.

MATCH (poi:PointOfInterest)
WHERE poi.id = "X0007"
WITH poi
OPTIONAL MATCH (poi)-[r]-(allRelatedNodes)
WHERE size((allRelatedNodes)--()) = 1    
DETACH DELETE poi, allRelatedNodes

Using Neo4j 3.0 and starting with the following graph...

Starting Sample Graph

And executing a close facsimile of the above query (listed below)...

MATCH (poi:Node)-[r]-(allRelatedNodes) 
WHERE poi.name = "A"
AND size((allRelatedNodes)--()) = 1    
DETACH DELETE poi, allRelatedNodes

I am left with this graph.

enter image description here

If that does not delete it all in one query you could use this instead and that should definitely take care of it.

MATCH (poi:PointOfInterest)-[r]-(allRelatedNodes) 
WHERE poi.id = "X007"
AND size((allRelatedNodes)--()) = 1
WITH poi, collect(allRelatedNodes) as allRelatedNodes
DETACH DELETE poi
WITH allRelatedNodes
UNWIND allRelatedNodes as node
DELETE node

Upvotes: 2

Related Questions