40

In SQL:

Delete From Person Where ID = 1;

In Cypher, what's the script to delete a node by ID?

(Edited: ID = Neo4j's internal Node ID)

Rm558
  • 4,621
  • 3
  • 38
  • 43

5 Answers5

64

Assuming you're referring to Neo4j's internal node id:

MATCH (p:Person) where ID(p)=1
OPTIONAL MATCH (p)-[r]-() //drops p's relations
DELETE r,p

If you're referring to your own property 'id' on the node:

 MATCH (p:Person {id:1})
 OPTIONAL MATCH (p)-[r]-() //drops p's relations
 DELETE r,p
Luanne
  • 19,145
  • 1
  • 39
  • 51
37

The cleanest sweep for a node with id "x" is

MATCH (n) where id(n) = x
DETACH DELETE n

https://neo4j.com/docs/cypher-manual/current/clauses/delete/#delete-delete-a-node-with-all-its-relationships

https://neo4j.com/docs/cypher-manual/current/functions/scalar/#functions-id

Brian Burns
  • 20,575
  • 8
  • 83
  • 77
Saad Khan
  • 481
  • 4
  • 2
5

Old question and answered, but to delete node when it has relationships, use DETACH

MATCH (n) where ID(n)=<your_id> 
DETACH DELETE n

or otherwise you get this:

Neo.ClientError.Schema.ConstraintValidationFailed: Cannot delete node<21>, because it still has relationships. To delete this node, you must first delete its relationships.

It's like SQL's CASCADE

O-9
  • 1,626
  • 16
  • 15
2

When the node is a orphan.

Start n=node(1)
Delete n;
Rm558
  • 4,621
  • 3
  • 38
  • 43
1

Following the link provided by @saad-khan, here's an example for getting the nodes and relationships ids. The code below shows the ids, so you can make sure that you're deleting everything related to the given ID.

MATCH (node)-[relation:HAS]->(value) where ID(node)=1234 RETURN ID(instance), ID(value), ID(r)

Ps.: ":HAS" is an example of an relationship.

arturvt
  • 641
  • 7
  • 9