简体   繁体   中英

Neo4J Cypher query - Null relationship

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.

  1. Your 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.
  2. By the way, the "p, c" in "MATCH p, c, p-[:lives]->c" is unnecessary and inefficient.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM