Search code examples
neo4jcypher

Get nodes which are not connected to specific node in Neo4j


I want to get all the nodes which are not connected to the given set of nodes. Suppose I've 5 nodes A,B,C,D,E. Now A->B->C are connected with the :Is_Friend relationship. Now I want all the nodes which are not connected to A (i.e D and E).

I tried this query but it's not working

MATCH (a:Friend{name:"A"})-[:Is_Friend_Of*]->(b:Friend) 
MATCH (c:Friend) 
WHERE NOT (c)-[:Is_Friend_Of]->(b)
RETURN c

Solution

  • Thi query should do what you want it to, however, I would caution that depending on the size of the number of unmatched friends in your database you could get a lot of matches.

    // match the single longest chain of friends in a :Is_Friend_Of relationship
    // starting with 'A' that is possible
    MATCH path=(a:Friend {name:"A"})-[:Is_Friend_Of*]->(b:Friend)
    WHERE NOT (b)-[:Is_Friend_Of*]->()
    WITH path
    
    // then find the other friends that aren't in that path
    MATCH (c:Friend) 
    WHERE NOT c IN nodes(path)
    RETURN c