6
votes

Perhaps this approach is wrong but I've built a cypher query using optional matches and collect. If there is data everything is fine, if not, collect returns null for the properties specified. It looks like this is expected as per the docs.

Ideally I'd like collect to return an empty array or null when there no match is made. I'm using the following...

MATCH (p) WHERE id(p) = 11
OPTIONAL MATCH (p) -[:car]- (c)
OPTIONAL MATCH (p) -[:driver]- (u)
RETURN {
  _id: id(p), name: p.name, type: p.type,
  cars: collect({_id: id(c), name: c.name}),
  drivers: collect({_id: id(u), name: u.email})
} AS place
1

1 Answers

13
votes

Try like this

MATCH (p) WHERE id(p) = 11
OPTIONAL MATCH (p) -[:car]- (c)
OPTIONAL MATCH (p) -[:driver]- (u)
RETURN {
  _id: id(p), name: p.name, type: p.type,
  cars: CASE WHEN c IS NOT NULL THEN collect({_id: id(c), name: c.name}) ELSE NULL END,
  drivers: CASE WHEN u IS NOT NULL THEN collect({_id: id(u), name: u.email}) ELSE NULL END
} AS place

This will check whether data is present to collect or not if present then it will return else null value will be returned