Sean Mackesey
Sean Mackesey

Reputation: 10959

Neo4j delete all nodes with a given label and their relationships in one query

I separate my Neo4j database into isolated sub-databases using labels. During development, I frequently need to wipe an entire sub-database clean. Currently I do this with:

MATCH (n:myLabel)-[r]-() DELETE n, r
MATCH (n:myLabel) DELETE n

I need two queries because I have to delete all relationships, at the same time as their nodes, but I don't know how to match unconnected nodes simultaneously. Is there a way to wipe out a whole subgraph marked by a label in a single query? I'm on Neo4j 2.2.1

Upvotes: 6

Views: 3184

Answers (2)

Kaan
Kaan

Reputation: 5794

From Neo4j docs (https://neo4j.com/docs/cypher-manual/current/clauses/delete/#delete-a-node-with-all-its-relationships):

To delete nodes and any relationships connected them, use the DETACH DELETE clause.

To delete all nodes matching label "myLabel", including any connected relationships, you could do this:

MATCH (n:myLabel) DETACH DELETE n

Upvotes: 0

Brian Underwood
Brian Underwood

Reputation: 10856

Here you go:

MATCH (n:myLabel) OPTIONAL MATCH (n)-[r]-() DELETE n, r

Upvotes: 10

Related Questions