Delete a subgraph from a database

hello, I have few graphs in my neo4j and I want to delete one of them that looks like this:

how can I do it with a query?
I Only know how to delete all the nodes in my db and realtionships with the command:
or one node each time with the command:
MATCH (n {name: 'Andy'})

Thank u and have a great day!

Hello @verachkaverachka :slight_smile:

I don't understand what is the issue?
Do you want to delete the whole graph or only a subgraph?


I want to delete the whole graph in this image , but in my neo4j database I have other graphs too that I didn't show in this image and I don't want to affect them when I delete this graph

A smart way would be to run the Weakly Connected Components algorithm from the GDS plugin on your database. Each subgraph will have its own community, then you will be able to delete all nodes and relationships from a community.

Hello @verachkaverachka, did you need more help?

1 Like

Thank you so much for your answers! I haven't tried yet your solutions I Will try them this week and if something won't work i'll let you know :)

1 Like

Hey :) i'm trying to understand how to delete this graph without touching any other graphs in my database that doesn't appear in the following picture, and I didn't quite understand how to use this weakly connected Componnent with the GDS plugin, can you elaborate a little more? how will be smart to create a query that will fit me this is the graph i'm trying to delete right now it starts with node named Graph


First, you must install GDS plugin on your database.

Then, you create a graph projection on the whole database:

CALL gds.graph.project(
YIELD graphName AS graph, nodeProjection, nodeCount AS nodes, relationshipProjection, relationshipCount AS rels

Then you run the WCC algorithm in write mode (each subgraph is a component and will have its own componentId):

CALL gds.wcc.write('graph', { writeProperty: 'componentId' })
YIELD nodePropertiesWritten, componentCount;

Then you delete the graph projection which is stored in-memory:

CALL gds.graph.drop('graph', false) YIELD graphName;

Finally, you can delete the subgraph based on the componentId (the query deletes the subgraph which has 0 as componentId) property stored on nodes (the query works on at least Neo4j 4.4 version):

WHERE n.componentId = 0
    WITH n

Or this query if you are under Neo4j 4.4 version:

CALl apoc.periodic.iterate(
    "MATCH (n) WHERE n.componentId = 0 RETURN n", 
    "DETACH DELETE n", {batchSize: 10000}
YIELD batches, total 
RETURN batches, total


thank you so much for your detailed answers! i'm going to try it now :) i'll let you know if i've completed it all successfully !

1 Like

Do I have to install apoc if i use version of neo4j that is under 4.4?

Yes you have to install APOC.

1 Like