19
votes

I have a neo4j db with the following:

a:Foo
b:Bar

about 10% of db have (a)-[:has]->(b)

I need to get only the nodes that do NOT have that relationship!

previously doing ()-[r?]-() would've been perfect! However it is no longer supported :( instead, doing as they suggest a

OPTIONAL MATCH (a:Foo)-[r:has]->(b:Bar) WHERE b is NULL RETURN a

gives me a null result since optional match needs BOTH nodes to either be there or BOTH nodes not to be there...

So how do i get all the a:Foo nodes that are NOT attached to b:Bar?

Note: dataset is millions of nodes so the query needs to be efficient or otherwise it times out.

2

2 Answers

33
votes

That would be

MATCH (a:Foo) WHERE not ((a)-[:has]->(:Bar)) RETURN a;
8
votes

This also works if you're looking for all singletons/orphans:

MATCH (a:Foo) WHERE not ((a)--()) RETURN a;