How To Clear Or Delete Neo4j Database?
I am sharing the best ways to clear or delete the Neo4j database as per your specific needs.
Neo4j Remove Clause
The REMOVE clause is used to remove properties from nodes or relationships. It is also used to remove labels from the nodes.
Remove Node properties
There are 2 ways to remove the property from a node. You can either use a REMOVE clause or a SET clause. Using SET, You can set the property value as null and it will remove the property because Neo4j doesn’t allow storing null properties. Storing null is equivalent to removing it.
Screenshot: Remove Node Properties
1. Remove node property using REMOVE Clause
|
|
2. Remove node property using SET clause
|
|
3. Remove all node properties. REMOVE clause can not be used to remove all the properties. Instead, SET can be used to set node = empty map, which will remove all the properties from node.
|
|
Remove Relationship properties
Removing properties from the relationship is identical to removing properties from the nodes. You just need to match the relationship and use the above syntax. For example:
|
|
Remove a label from a node
|
|
Neo4j Delete Clause
The DELETE
is used to delete nodes, relationships, or paths.
Delete Relationships
We may need this query when you accidentally created incorrect relationships or you decided to change the data model.
|
|
Delete Nodes
Please note that we can not delete a node without deleting the connected relationships. We should either delete all the relationships first or delete them along with the node or use DETACH DELETE on a node that will detach node from connected node and delete it. OPTIONAL MATCH clause is used to make sure that nodes without relationships are also deleted, without OPTIONAL MATCH nodes having no relationships will not match the pattern and will not be deleted.
|
|
If there are no relationships to the node you can simply delete the node as follows:
|
|
Completely Clear or Delete Neo4j data
|
|
Above Cypher snippet works fine for small databases but for big databases, you need to delete the data in auto-commiting transactions which deletes data in multiple transactions and prevents the Neo4j throwing out of memory error. The following query does not work for older versions of the Neo4j(< version 4.4). If it doesn’t work for you, you can use APOC Library to delete the database using the periodic commit procedure.
|
|
Delete Neo4j data with auto committing Transactions