Search for nodes that do not have a specific relationship (Cypher / neo4j)

I have a neo4j db with the following:

a:Foo b:Bar 

about 10% db have (a) - [: has] β†’ (b)

I need to get only nodes that DO NOT have this relationship!

earlier doing () - [r?] - () would be great! however it is no longer supported :( instead, doing as they suggest "ADDITIONAL MATCH (a: Foo) - [r: has] β†’ (b: Bar) WHERE b - NULL RETURN a" gives me a null result, since optional match requires that the BOTH nodes are either there or the BOTH nodes are not there ...

So, how can I get all the "a: Foo" nodes that are NOT bound to "b: Bar"?

Note. A dataset is millions of nodes, so a query must be efficient or it will expire otherwise.

Thank!

+11
database neo4j cypher
Sep 04 '14 at 19:04
source share
2 answers

This will

 MATCH (a:Foo) WHERE not ((a)-[:has]->(:Bar)) RETURN a; 
+22
Sep 04 '14 at 20:14
source share

This also works if you are looking for all the singles / orphans:

 MATCH (a:Foo) WHERE not ((a)--()) RETURN a; 
+3
Aug 29 '16 at 14:32
source share



All Articles