Search code examples
neo4jrelationshipcypherneo4jphp

How to find node with no incoming relationship in neo4j


I am having 2 node types lets say of type 'Student' and 'Teacher'

Student have {id, name}.
Teacher have {id, name}.

Student can have optional relationship with Class node as 'TEACHES'.

(t:Teacher)-[r:TEACHES]->(c:Student).

[r:TEACHES] - Optional relationship. (present or may not present)

I want to find "Student" nodes who don't have teacher. i.e There is no any incoming relationship "TEACHES"

Please help.


Solution

  • Here's a simple data setup, along with the query at the bottom you need to solve your problem. Essentially, you want to query for situations where a relationship doesn't exist. The syntax here is for neo4j 2.0, so the answer would be slightly different for older versions.

    neo4j-sh (?)$ create (t:Teacher {name:"Bob"})-[r:TEACHES]->(s:Student {name:"Mary"});
    +-------------------+
    | No data returned. |
    +-------------------+
    Nodes created: 2
    Relationships created: 1
    Properties set: 2
    Labels added: 2
    19 ms
    
    neo4j-sh (?)$ create (t:Teacher {name:"Mark"});
    +-------------------+
    | No data returned. |
    +-------------------+
    Nodes created: 1
    Properties set: 1
    Labels added: 1
    5 ms
    
    neo4j-sh (?)$ MATCH (s:Student) WHERE NOT (s)<-[:TEACHES]-(:Teacher) RETURN s