Reputation: 858
I am fairly new to Neo4J and have a problem in a Cypher query.
I write cypher queries through Neo4J java and my Neo4J database is designed as follows:
I have a user node with attributes such as id, name, age, email, gender and a node city. Every user is related to a city node(with attributes id, name) by a relationship (lives). However there can be a case when a user is not associated with city.
Now my scenario of the query is such that I want to fetch all details of user and the city he lives in, in a single query which is.
match p, c, p-[:lives]->c where p.type = 'com.Person' and c.type='com.City' and p.id = 12345 return p.name, p.age, p.email, p.gender, c.name;
The query works well when user is related to a city, but it fails in case when a user is not associated with a city.
Could you please help me with a query that can handle both the scenarios.
Upvotes: 0
Views: 1598
Reputation: 66957
MATCH
and WHERE
clauses are actually requiring that all matched p
must be associated with a city. You have to use the OPTIONAL MATCH
clause for optional matches.To get the results you want, try the following (c.name
will be null
if there is no associated city):
MATCH (p {type: "Person", id: 12345})
OPTIONAL MATCH (p)-[:lives]->(c {type: "City"})
RETURN p.name, p.age, p.email, p.gender, c.name;
Also, I would strongly suggest the use of the labels Person
and City
for your p
and c
nodes (instead of the type
properties). That would make your queries much more efficient and also clearer. If you made this change to your nodes, the faster queries would look like:
MATCH (p:Person {id: 12345})
OPTIONAL MATCH (p)-[:lives]->(c:City)
RETURN p.name, p.age, p.email, p.gender, c.name;
Upvotes: 3