简体   繁体   中英

Collecting results with optional nodes in Neo4j cypher results

I have a person node in my graph:

CREATE (:Person {id: "1" name:"foo"})

Which can optionally have one or more phone numbers associated with it. I then do the following to query the person:

MATCH (p:Person)
WHERE p.id = "1"
WITH p
MATCH p-[?:PHONE]->ph
RETURN p.id, p.name, COLLECT([ph.id, ph.number]) AS phones

This works fine when the person has phone numbers:

"1", "foo", [["p1", "111-1111"], ["p2", "111-1112"]]

But in the case that the person doesn't have any phone numbers, I get the following result:

"1", "foo", [[null, null]]

How can I return the the following instead if there are no phone numbers?

"1", "foo", null

You might use the "CASE" expression to return two different result for the two cases,

MATCH (p:Person)
WHERE p.id = "1"
WITH p
MATCH p-[?:PHONE]->ph
WITH p.id as pid, p.name as pname, collect([ph.id, ph.number]) as phones
RETURN pid, pname, CASE WHEN all ( x in head(phones) where x = NULL ) THEN  NULL ELSE phones END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM