oht
oht

Reputation: 357

Optional match extends query

When I add an optional match to my already working query the selection is expanded.

I have a structure regarding players in games as follows (player)-[got]->(result)-[in]->(game)

And as players oppose each other things will look like this in the final data (player_1)-[got]->(result_1)-[in]->(game)<-[in]-(result_2)-[got]-(player_2)

Given a list of result_1 ids I try to find corresponding result_2

The basic query

MATCH (r:Result)-[:In]->(g:Game)<-[:In]-(or:Result)  
WHERE r.id IN [30,32] 
RETURN r, or, g, m

returns exactly what I expect:

  1. (30)-(g1)-(or1)
  2. (32)-(g2)-(or2)

But games can also be in an (optional) match and this query

MATCH (r:Result)-[:In]->(g:Game)<-[:In]-(or:Result)     
OPTIONAL MATCH (g)<-[:Contains]-(m:Match) 
WHERE r.id IN [30,32] 
RETURN r, or, g, m

returns

  1. (30)-(g1)-(or1)
  2. (32)-(g2)-(or2)
  3. (33)-(g3)-(or3)
  4. (n)-(gn)-(orn)
  5. Whatever else happens to match the structure p-r-g-r-p but with no regard to the list [30,32]

I do suspect that it has something to do with the mirrored nature of the data because if I remove r from the returned values I still get (30) and (32) back as or but I cannot figure out why and thus how to stop it.

I've tried to add a With before the optional but it makes no difference.

Upvotes: 0

Views: 32

Answers (1)

cybersam
cybersam

Reputation: 66967

The WHERE clause modifies the immediately preceding [OPTIONAL] MATCH or WITH clause.

You need to move your WHERE clause so it is right after the initial MATCH, so that it will limit r as you intended. Like this:

MATCH (r:Result)-[:In]->(g:Game)<-[:In]-(or:Result)     
WHERE r.id IN [30,32] 
OPTIONAL MATCH (g)<-[:Contains]-(m:Match) 
RETURN r, or, g, m

Upvotes: 2

Related Questions