I want to delete every node and edge of any type from a Neo4j database. There are different ways of deleting nodes and edges suggested on SO. However, since my database is huge, and since all these methods rely on first querying for edges/nodes and then deleting them, which leads to loading (at least their indexes) into memory, these methods fail for my use case with the out-of-memory error. See the following example.
match ()-[r]->() delete r
match (n) delete n
Neo.TransientError.General.OutOfMemoryError: There is not enough memory to perform the current task. Please try increasing 'dbms.memory.heap.max_size' in the neo4j configuration (normally in 'conf/neo4j.conf' or, if you are using Neo4j Desktop, found through the user interface) or if you are running an embedded installation increase the heap by using '-Xmx' command line flag, and then restart the database.
For different reasons, I cannot increase the amount of configured memory.
One radical solution is to delete the database's files which would lead to deleting the database effectively (even resetting the indexes). In my use case, this approach has its downsides, e.g., some of our applications rely on a set import path to bulk load data (e.g., Neo4jDesktop\relate-data\dbmss\dbms-...\import\) where deleting and re-creating the database requires updating all those dependent applications.
I was wondering if there is any efficient approach other than these to delete all nodes and edges from a huge Neo4j database---ideally without needing to loading/query the nodes/edges first.
If you are using Neo4j 4.3 and above, you can simply use:
DROP DATABASE database_name IF EXISTS <-- Best Way
OR you can use use CALL syntax, like this:
MATCH (n)
CALL { WITH n
DETACH DELETE n
} IN TRANSACTIONS OF 10000 ROWS;
The above query might not work on Neo4j Browser. To run it on neo4j Browser, try this:
:auto MATCH (n)
CALL { WITH n
DETACH DELETE n
} IN TRANSACTIONS OF 10000 ROWS;
Finally, if your version is less than 4.x, you can try the APOC as suggested in another answer, or simply run this query multiple times until the output is zero.
MATCH (n)
WITH n LIMIT 10000
DETACH DELETE n
RETURN count(*);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With