How to delete a node in Neo4j?

  • Read
  • Discuss

A node is a data/record represented by a circle in a graph database. In Neo4j, the DELETE clause is used to delete nodes, relationships or paths.

In this article you’ll learn how to:

  • Delete a single node in Neo4j
  • Delete a node with all its relationships in Neo4j
  • Delete all nodes and relationships in Neo4j

It is not possible to delete nodes with relationships connected to them without also deleting the relationships. This can be done by either explicitly deleting specific relationships, or by using the DETACH DELETE clause.

DELETE Clause

In Neo4j to delete a node or relations between nodes you have to use the DELETE clause. To delete any node you need DELETE clause with the MATCH statement, the MATCH statement data will find the specific node and whichever node is matched with the statement that node will be vanished.

The following graph is used for the examples below. It shows four actors, three of whom ACTED_IN the Movie The Matrix (Keanu Reeves, Carrie-Anne Moss, and Laurence Fishburne), and one actor who did not act in it (Tom Hanks).


To recreate the graph, run the following query in an empty Neo4j database:

CREATE
  (keanu:Person {name: 'Keanu Reeves'}),
  (laurence:Person {name: 'Laurence Fishburne'}),
  (carrie:Person {name: 'Carrie-Anne Moss'}),
  (tom:Person {name: 'Tom Hanks'}),
  (theMatrix:Movie {title: 'The Matrix'}),
  (keanu)-[:ACTED_IN]->(theMatrix),
  (laurence)-[:ACTED_IN]->(theMatrix),
  (carrie)-[:ACTED_IN]->(theMatrix)

Delete single node in Neo4j

To delete a single node, use the DELETE clause:

MATCH (n:Person {name: ‘Tom Hanks’})
DELETE n

This deletes the Person node Tom Hanks. This query is only possible to run on nodes without any relationships connected to them.

Delete relationships only in Neo4j

It is possible to delete a relationship while leaving the node(s) connected to that relationship otherwise unaffected.

MATCH (n:Person {name: 'Laurence Fishburne'})-[r:ACTED_IN]->()
DELETE r

This deletes all outgoing ACTED_IN relationships from the Person node Laurence Fishburne, without deleting the node.

Delete a node with all its relationships in Neo4j

To delete nodes and any relationships connected to them, use the DETACH DELETE clause.

MATCH (n:Person {name: 'Carrie-Anne Moss'})
DETACH DELETE n

This deletes the Person node Carrie-Anne Moss and all relationships connected to it.

Delete all nodes and relationships in Neo4j

It is possible to delete all nodes and relationships in a graph.

MATCH (n)
DETACH DELETE n

This will delete all the nodes and all the relationships present in the graph.

If you run the query to view all the nodes in the graph, you’ll get no node.

Leave a Reply

Leave a Reply

Scroll to Top