Bill
Bill

Reputation: 25555

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

Upvotes: 2

Views: 1031

Answers (1)

Lisa Li
Lisa Li

Reputation: 2592

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

Upvotes: 4

Related Questions