Search code examples
neo4jrelationshipcypherneo4jphp

Delete node with all incoming and outgoing relationships


I want to delete node with all incoming and outgoing relationships.

This incoming and outgoing relationships are optional.

(t:Teacher)-[:TEACHES]->(s:Student)
(s:Student)-[:ATTENDS]->(c:Class)

Student node have optional relationship with Teacher and optional relationship with Class.

I want to delete Student node with {id:1}.

I know how to delete all nodes and relationships with:

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r

But not able to convert it for specific node. Please help.


Solution

  • Just add the discriminating property to the first match clause

    MATCH (s:Student {id:1})
    OPTIONAL MATCH s-[r]-()
    DELETE r, s
    

    If instead by id you mean the internal node id and not a property that you have set, then

    MATCH (s)
    WHERE ID (s) = 1
    OPTIONAL MATCH s-[r]-()
    DELETE r, s
    

    should work. It is irregular and usually bad to lay hold of nodes by their internal id.