TenTonBonton
TenTonBonton

Reputation: 119

How can I list only nodes that were not found using Cypher?

I have a list of capital cities. I want to see if I have all of them. How can I see which cities I don't have inside? My query looks like this at the moment:

OPTIONAL MATCH (n:Captial {name: 'London'})
RETURN n.name
UNION
OPTIONAL MATCH (n:Captial {name: 'Paris'})
RETURN n.name
UNION
OPTIONAL MATCH (n:Captial {name: 'Berlin'})
RETURN n.name
UNION
OPTIONAL MATCH (n:Captial {name: 'Rome'})
RETURN n.name

This doesn't seem elegant and on top of everything as a result I get:

London
Paris
Berlin
null

To me it means that I don't have Rome in my database. But can the output be Rome only, and not list off all cities that are there and null for one that isn't there?

Upvotes: 2

Views: 47

Answers (2)

MPesi
MPesi

Reputation: 357

In Memgraph, it could be solved similarly:

WITH ['London', 'Paris', 'Berlin', 'Rome'] AS capitals
UNWIND capitals as capital
OPTIONAL MATCH (c:Capital {name: capital})
WITH capital, c
WHERE c IS NULL
RETURN capital

After you define your list and unwind it to get each element, you can use OPTIONAL MATCH (we're not using MATCH since OPTIONAL allows null) to match each item of the list to the name property of nodes. If there are no such nodes we return that capital as an output.

Upvotes: 1

Christoffer Bergman
Christoffer Bergman

Reputation: 286

I don't really know Memgraph, but in Neo4j I would solve it like this:

UNWIND ['London', 'Paris', 'Berlin', 'Rome'] AS capital
OPTIONAL MATCH (n:Captial {name: capital})
WITH n, capital WHERE n IS NULL
RETURN capital

Upvotes: 1

Related Questions