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.

The REMOVE clause is used to remove properties from nodes or relationships. It is also used to remove labels from the nodes.

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

1
2
MATCH (p:Product)
REMOVE p.discount;

2. Remove node property using SET clause

1
2
MATCH (p:Product)
SET p.name=null;

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.

1
2
MATCH (p:Product)
SET p={};

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:

1
2
MATCH (n:Product)-[r:HAS_DISCOUNT]->(d:Discount)
REMOVE r.occasion
1
2
MATCH (n:Product)
REMOVE n:Product

The DELETE is used to delete nodes, relationships, or paths.

We may need this query when you accidentally created incorrect relationships or you decided to change the data model.

1
2
MATCH (:Product)-[c:HAS_CATEGORY]->(:Category)
DELETE c

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.

1
2
3
MATCH (p:Product)
OPTIONAL MATCH (p)-[r:HAS_CATEGORY]->(:Category)
DELETE p, r

If there are no relationships to the node you can simply delete the node as follows:

1
2
MATCH (p:Product)
DELETE p
1
2
MATCH (n)
DETACH DELETE n

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.

1
2
3
4
5
:auto MATCH (n)
CALL {
    WITH n
    DETACH DELETE n
} IN TRANSACTIONS OF 100000 ROWS

Delete Neo4j data with auto committing Transactions

  1. Neo4j REMOVE documentation
  2. Neo4j DELETE documentation

Related Content