Neo4j - Include Null values for relationships that dont exist

Viewed 134

I have a non-relational DB and using Neo4j cypher to query. I have seen this question up multiple times but I cant seem to get it to work for my query. Basically I am returning all the nodes of a specific type from the DB. Type of Node is called Person. From that I am finding the node related to the original Person from the relationship MARRIED_TO. Not all of the original nodes have the MARRIED_TO relationship. For these I want to return null. I have tried using the OPTIONAL MATCH but that does not seem to work either.

OPTIONAL MATCH (p:Person)-[m:MARRIED_TO]-(p2:Person) 
Return p.name as Name, p2.name as Spouse
ORDER By Name, Spouse

This returns the original nodes with relationships, but not the nodes with no corresponding MARRIED_TO relationship.

And below just returns two null columns

OPTIONAL MATCH (p:Person)-[m:MARRIED_TO]-(p2:Person) 
WHERE (m) is null
Return p.name as Name, p2.name as Spouse
ORDER By Name, Spouse

Thanks for any help that you may be able to provide.

1 Answers
MATCH (p:Person) 
WITH p 
OPTIONAL MATCH (p)-[:MARRIED_TO]-(p2) 
RETURN p.name, p2.name

This returns

╒═══════════╤═════════╕
│"p.name"     │"p2.name"│
╞═══════════╪═════════╡
│"Anna"       │"Ben"    │
├───────────┼─────────┤
│"Ben"        │"Anna"   │
├───────────┼─────────┤
│"Catherine"  │null     │
└───────────┴─────────┘

The trick is to MATCH all the nodes you want to return (all Person nodes in this case), and then OPTIONAL MATCH their spouse.

Related