Deleting All Nodes and Relationships

Neo4j

Seems that I am doing this a lot: deleting my entire graph (all nodes and relationships) and rebuilding from scratch. I guess that this is part of the learning process.

Route 1: Delete Relationships then Nodes

A relationship is constrained to join a start node to an end node. Every relationship must be associated with at least one node (a relationship may begin and end on the same node). No such constraint exists for nodes. As a result relationships must be deleted before nodes are deleted.

Delete all relationships using either

$ START r = RELATIONSHIP(*) DELETE r;

or

$ MATCH ()-[r]-() DELETE r;

Then delete the nodes with

$ MATCH (n) DELETE n;

Route 2: Detach and Delete

Using DETACH DELETE it’s possible to delete relationships and nodes at once.

$ MATCH (n) DETACH DELETE n;

Check

Confirm that all nodes and relationships have gone.

$ MATCH (n) RETURN COUNT(n);
$ MATCH ()-[r]->() RETURN COUNT(r);

Or, alternatively:

$ START n = NODE(*) return COUNT(n);  
$ START r = RELATIONSHIP(*) return COUNT(r);

Categorically Variable