biliboc
biliboc

Reputation: 737

Neo4j v.2.0.0 OPTIONAL MATCH query

In previous versions I was able to run this query and get back the nodes that DO NOT have inbound <PROPERTY> relations:

start e=node:entity_name_ft("name:doe") MATCH (e)<-[r?:PROPERTY]-() WHERE r IS NULL return e;

In the new version the ? operator is no longer accepted. I must use OPTIONAL MATCH:

start e=node:entity_name_ft("name:doe") OPTIONAL MATCH (e)<-[r:PROPERTY]-() WHERE r IS NULL return e;

The problem is that if I use it like in the query below I also get the nodes that DO HAVE inbound <PROPERTY> relations!

How do I return only the nodes that DO NOT have inbound <PROPERTY> relations?

Upvotes: 0

Views: 458

Answers (1)

Chris Vest
Chris Vest

Reputation: 8672

The WHERE clause in your query is applied to the output of the OPTIONAL MATCH clause - not to the combined output.

You can break out the context of the WHERE clause to get what you want, with WITH:

neo4j-sh (?)$ create ({x: 1}),({x: 2})<-[:PROPERTY]-({x: 3});                                
+-------------------+
| No data returned. |
+-------------------+
Nodes created: 3
Relationships created: 1
Properties set: 3
10 ms
neo4j-sh (?)$ match n optional match (n)<-[r:PROPERTY]-() with n, r where r is null return n;
+--------------+
| n            |
+--------------+
| Node[4]{x:1} |
| Node[5]{x:3} |
+--------------+
2 rows
4 ms
neo4j-sh (?)$

This behaviour is documented in our description of WHERE: http://docs.neo4j.org/chunked/stable/query-where.html

Upvotes: 4

Related Questions