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

2

6

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

Cuccuckold answered 30/4, 2015 at 13:34 Comment(0)
C
10

Here you go:

MATCH (n:myLabel) OPTIONAL MATCH (n)-[r]-() DELETE n, r
Craftwork answered 30/4, 2015 at 13:42 Comment(2)
This will not work : "Parentheses are required to identify nodes in patterns". Should be MATCH (n:myLabel) OPTIONAL MATCH (n)-[r]-() DELETE n, rTraveler
Thanks, fixed! I think that this was written before Neo4j started requiring that syntax :)Craftwork
F
0

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
Flawy answered 14/4 at 5:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.