Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

neo4j optional match and null

Tags:

neo4j

cypher

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
like image 353
user2704643 Avatar asked May 05 '15 04:05

user2704643


People also ask

What is optional match in Neo4j?

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.

Which statement about NULL is not true in Neo4j?

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 .

What does match do in Neo4j?

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.


1 Answers

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

like image 98
Satish Shinde Avatar answered Nov 15 '22 11:11

Satish Shinde