Neo4j Cypher Basics: DELETE, DETACH DELETE, SET, REMOVE
1. DELETE
The DELETE
command is used to remove nodes or relationships from the graph. To delete a node, all its relationships must be removed first.
Syntax
DELETE node_name
Example
DELETE n
This command deletes the node n
, but will fail if n
has any relationships.
2. DETACH DELETE
The DETACH DELETE
command allows you to delete a node and all its associated relationships in one command.
Syntax
DETACH DELETE node_name
Example
DETACH DELETE n
This command deletes the node n
along with all the relationships connected to it.
3. SET
The SET
command is used to assign properties to nodes or relationships. It can also be used to update existing properties.
Syntax
SET node_name.property = value
Example
SET n.name = 'New Name'
This command updates the property name
of the node n
to 'New Name'
.
4. REMOVE
The REMOVE
command is used to delete properties from nodes or relationships.
Syntax
REMOVE node_name.property
Example
REMOVE n.name
This command removes the property name
from the node n
.
FAQ
What happens if I try to DELETE a node with existing relationships?
The DELETE command will fail with an error message indicating that the node cannot be deleted due to existing relationships.
Can I use SET to add multiple properties at once?
No, you need to use separate SET commands for each property or use a map to set multiple properties in one command.
Is there a way to delete nodes based on a condition?
Yes, you can use a MATCH clause to find nodes that meet certain criteria before using DELETE or DETACH DELETE.