Search code examples
cyphermemgraphdbopencyphermemgraph

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?


Solution

  • 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.