Deleting Nodes and Relationships

Deleting all nodes and relationships in a Neo4j database is very simple. Here is an example that does just that:

MATCH (n) DETACH DELETE n;

The DETACH keyword specifies to remove or “detach” all relationships from a particular node before deletion. If relationships exist on a node at the time deletion is attempted, an exception will be thrown and you might see a message like “To delete this node, you must first delete its relationships“.

Deleting Nodes only

If no relationships exist on the nodes in your database, you can simply remove “DETACH” from the query above. For example:

MATCH (n) DELETE n;

Unique Constraint Exceptions after Deleting Nodes

If unique constraints exist on nodes, you may see exceptions when trying to recreate nodes that previously existed. Dropping unique constraints before or after deleting nodes can help you avoid these issues.

Here is example of dropping a unique constraint on the :User label and the username property:

DROP CONSTRAINT ON (user:User) ASSERT user.username IS UNIQUE;

Leave a Reply

Delete all Nodes and Relationships in a Neo4j Database