Iván
Iván

Reputation: 1060

OPTIONAL MATCH in Cypher not returning values

I'm trying to get nodes "A" so that it doesn't have a connection with any "B" OR that B doesn't has a connection with "C".

This is my query right now:

MATCH (a:A)
OPTIONAL MATCH (a) -- (b:B), (b) -- (c:C)
WITH *
WHERE (
    b IS NULL
    OR
    c IS NULL
)

RETURN *

The "a" results are correct. The problem is, that "b" is always null ("c" too, but that's expected).

I'm not using relationship predicates in the where because I need those nodes. This is a simple example, but I'm chaining more relationship levels and more filters (AND & OR)

Upvotes: 0

Views: 439

Answers (1)

Tomaž Bratanič
Tomaž Bratanič

Reputation: 6534

Your issue is that you need to split the OPTIONAL MATCH into two matches.

MATCH (a:A)
OPTIONAL MATCH (a) -- (b:B)
OPTIONAL MATCH (b) -- (c:C)
WITH *
WHERE (
    b IS NULL
    OR
    c IS NULL
)

RETURN *

When you are doing a single OPTIONAL MATCH, you are searching for a complete pattern and if it doesn't exist, then it won't be returned.

Upvotes: 1

Related Questions