Balael
Balael

Reputation: 213

JOIN in a Cypher Query?

It seems I do not understand OPTIONAL MATCH correctly.

I have a node (t) that always exists. This node (t) can have relations to other nodes (q), (o) - maybe to both or just one of them.

I am trying to catch in one statement something like

"Show me all information for node (t) and if there is a related node (o) then also all of (o) and if there is a node (q) then also for (q) - if one of them is not available show what you have"

I can do one of both qith a match and an optional match like

MATCH (t) -- (o) WHERE t.id = "1234" 
OPTIONAL MATCH (t) -- (q) 
RETURN q,t,o

I succeed when I have a path between (t) and (o) no matter if I have (q) or not. But I fail when I do not have (o) and though have (q). If I switch and put (q) in the first row and ((o) in the second its just vice versa, I always loose one of them.

How would I need to query to get either both (o),(q) or just one of them no matter which of them are there?

EDIT

  1. All nodes (t), (o) and (q) have additional labels
  2. I didnt put the query in the right way as I thought this doesnt matter, so the query which fails was MATCH (o:Label3) -- (t:Label1) WHERE t.id = "1234" OPTIONAL MATCH (q:Label2) -- (t:Label1) RETURN q,t,o

Upvotes: 3

Views: 4621

Answers (2)

Bruno Peres
Bruno Peres

Reputation: 16373

"Show me all information for node (t) and if there is a related node (o) then also all of (o) and if there is a node (q) then also for (q) - if one of them is not available show what you have"

If o and q have unique ids you can do it with two OPTIONAL MATH. This way:

MATCH (t) WHERE t.id = "1234"
OPTIONAL MATCH (t) -- (o {id:567})
OPTIONAL MATCH (t) -- (q {id:568}) 
RETURN q,t,o

Upvotes: 1

cybersam
cybersam

Reputation: 67044

If you just want to get a collection of all nodes connected to t:

MATCH (t) WHERE t.id = "1234"
OPTIONAL MATCH (t) -- (o)
RETURN t, COLLECT(o) AS others;

Upvotes: 4

Related Questions