Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding nodes that do not have specific relationship (Cypher/neo4j)

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.

like image 500
Diaspar Avatar asked Sep 04 '14 19:09

Diaspar


2 Answers

That would be

MATCH (a:Foo) WHERE not ((a)-[:has]->(:Bar)) RETURN a;
like image 50
Jan Van den bosch Avatar answered Oct 16 '22 01:10

Jan Van den bosch


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

MATCH (a:Foo) WHERE not ((a)--()) RETURN a;
like image 26
MAJ Avatar answered Oct 15 '22 23:10

MAJ