This site is not optimized for Internet Explorer 9 and lower. Please choose another browser or upgrade your existing browser in order get the best experience of this website.

Understanding DETACH DELETE in Cypher

February 26, 2016

Neo4j Cypher DETACH DELETE SequenceDETACH DELETE in Cypher is an example of why Cypher is one of my favorite ways of interacting with the Neo4j graph database. The declarative graph query language is constantly evolving to ease the requirements of querying Neo4j. This benefit in ease of interaction, however, can often further remove the query writer from needing to understand the inner workings of the Neo4j graph database being queried.

Whenever I cover node deletion in my Neo4j trainings I always mention DETACH DELETE as a convenience method for what we just covered because just like in mathematics, you don’t always want to be stuck plugging in numbers to a formula. To grow past that and deepen your understanding it becomes necessary to understand why the formula works the way it does. So let’s dive in…

Neo4j Referential Integrity Guarantee

Within the Neo4j graph database, there’s a guarantee that each relationship will always have a starting and ending node. This guarantee of referential integrity is core to the principles of reliability in which Neo4j concentrates its write architecture. To achieve this, ever time a relationship is being created or modified, Neo4j locks the nodes on both sides of the relationship.

Deleting Relationships with DETACH DELETE

This guarantee on write will also need to be considered whenever a node is being deleted. Neo4j carries out a constraint (upon commit) in which relationships must possess a valid start and end node. This is one reason why, before a node is removed, all its relationships must first be deleted. If a node were to be removed without deleting all relationships, there would be dangling relationships left behind.

Such relationships, considered as first class citizens within the graph, would already be violating their referential guarantee, since they would no longer possess a start and end node. Being unable to cross a relationship and get to the node on the other side will lead to breakdown in the construct of the graph.

Before Neo4j 2.3.x, removing a node and its relationships would be done in Cypher through, for example:

MATCH (n:Movie {title: "The Matrix"}) OPTIONAL MATCH (n)-[r]-() DELETE r, n;

Starting in Neo4j 2.3.x, DETACH DELETE was brought into Cypher as a simple format for removing a node and its relationships. An example would be:

MATCH (n:Movie {title: "The Matrix"}) DETACH DELETE n;

In summary, when removing a node without DETACH DELETE, relationships of a node will not be removed by default so you need to handle their removal, but when removing a node with DETACH DELETE, relationships of the node will be removed as well.