What's the Cypher script to delete a node by ID?
Asked Answered
A

6

43

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)

Ashkhabad answered 26/1, 2015 at 4:19 Comment(0)
L
67

(Answer updated for 2024!)

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

MATCH (p:Person) where elementId(p)=1
DETACH DELETE p

Assuming you're referring to Neo4j's (legacy) internal id:

MATCH (p:Person) where ID(p)=1
DETACH DELETE p

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

 MATCH (p:Person {id:1})
 DETACH DELETE p
Latton answered 26/1, 2015 at 4:40 Comment(3)
You could use DETACH DELETE instead of the optional matchWenn
What is 'Person' in this case? is it the 'name" property?Derangement
This works only if you don't want to delete the content in ().Vermouth
D
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

Diatomite answered 2/4, 2019 at 16:41 Comment(0)
A
2

When the node is a orphan.

Start n=node(1)
Delete n;
Ashkhabad answered 26/1, 2015 at 5:4 Comment(0)
V
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.

Vermouth answered 19/1, 2017 at 19:56 Comment(0)
T
0

Update 2023: the function id is now deprecated, it is advised to use the function elementId instead.

It should be noted that the id returned by elementId looks like this:
4:360c4f42-4aba-47aa-8d1c-dc543cb0cfba:179

To delete the node:

MATCH (n) WHERE elementId(n) = "4:360c4f42-4aba-47aa-8d1c-dc543cb0cfba:179"
DETACH DELETE n;
Thrippence answered 5/1, 2024 at 17:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.