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
An OPTIONAL MATCH matches patterns against your graph database, just like a MATCH does. The difference is that if no matches are found, OPTIONAL MATCH will use a null for missing parts of the pattern. OPTIONAL MATCH could be considered the Cypher equivalent of the outer join in SQL.
null is not equal to null . Not knowing two values does not imply that they are the same value. So the expression null = null yields null and not true .
The MATCH clause allows you to specify the patterns Neo4j will search for in the database. This is the primary way of getting data into the current set of bindings. It is worth reading up more on the specification of the patterns themselves in Patterns.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With