Neo4j: Get all nodes in a graph, even those that are unconnected by relationships
Asked Answered
O

4

52

Using Cypher how can I get all nodes in a graph? I am running some testing against the graph and I have some nodes without relationships so am having trouble crafting a query.

The reason I want to get them all is that I want to delete all the nodes in the graph at the start of every test.

Orthodontics answered 15/10, 2012 at 20:58 Comment(0)
N
102

So, this gives you all nodes:

MATCH (n)
RETURN n;

If you want to delete everything from a graph, you can do something like this:

MATCH (n)
OPTIONAL MATCH (n)-[r]-() 
DELETE n, r;

Updated for 2.0+

Edit: Now in 2.3 they have DETACH DELETE, so you can do something like:

MATCH (n)
DETACH DELETE n;
Nernst answered 15/10, 2012 at 23:14 Comment(2)
Will this delete the root node? I want to keep him.Orthodontics
Ok, then add where ID(n) <> 0 after the match.Nernst
C
14

Would this work for you?

START a=node:index_name('*:*')

Assuming you have an index with these orphaned nodes in them.

Criticism answered 15/10, 2012 at 21:11 Comment(2)
Thanks Jason, never seen that syntax before +1Orthodontics
The syntax is referenced here: docs.neo4j.org/chunked/snapshot/…Asseveration
B
7

This just works fine in 2.0:

    MATCH n RETURN n
Beersheba answered 23/2, 2014 at 12:6 Comment(1)
Using neo4j, parentheses are mandatory : MATCH (n) RETURN n;Stubbed
S
0

If you need to delete some large number of objects from the graph, one needs to be mindful of the not building up such a large single transaction such that a Java OUT OF HEAP Error will be encountered.

If your nodes have more than 100 relationships per node ((100+1)*10k=>1010k deletes) reduce the batch size or see the recommendations at the bottom.

With 4.4 and newer versions you can utilize the CALL {} IN TRANSACTIONS syntax.

MATCH (n:Foo) where n.foo='bar'
CALL { WITH n
DETACH DELETE n
} IN TRANSACTIONS OF 10000 ROWS;

With 3.x forward and using APOC

call apoc.periodic.iterate("MATCH (n:Foo) where n.foo='bar' return id(n) as id", "MATCH (n) WHERE id(n) = id DETACH DELETE n", {batchSize:10000})
yield batches, total return batches, total

For best practices around deleting huge data in neo4j, follow these guidelines.

Selfsealing answered 4/3, 2022 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.