Tony Ennis
Tony Ennis

Reputation: 12289

Cypher match a node but allow the relationship to be optional

I have this (a {...})-[r]->(b)

In my query, I always want 'a'. I will take r and b if I can get them.

I tried

optional match (a {...})-[r]->(b)

but when r or b are not present the entire match collapses.

This works:

optional match (a {...})
optional match (a)-[r]->(b)

clunky and hacky.

How can I do this?

Upvotes: 1

Views: 91

Answers (1)

Supamiu
Supamiu

Reputation: 8731

You can split your query into two parts, the optional one, and the non-optional one:

Match (a:Label {...})
Optional Match (a)-[r]->(b) with a,r,b
//Do whatever you want with a,r and b here

Using this, you will have a for sure, and optionally, r and b.

Upvotes: 3

Related Questions