cancel
Showing results forΒ
Did you mean:Β

Head's Up! Site migration is underway. Phase 2: migrate recent content

## How does this work - Multiple MATCH/OPTIONAL MATCH statements with WHERE

Node Clone

Hello fellow Neo4jers/ians!
Going through the lessons under Querying with Cypher and a question -

Related note from the Cypher Manual page -

In the case of multiple MATCH / OPTIONAL MATCH clauses, the predicate in WHERE is always a part of the patterns in the directly preceding MATCH / OPTIONAL MATCH . Both results and performance may be impacted if the WHERE is put inside the wrong MATCH clause.

Query -
MATCH (valKilmer:Person)-[:ACTED_IN]->(m:Movie)
MATCH (actor:Person)-[:ACTED_IN]->(m)
WHERE valKilmer.name = 'Val Kilmer'
RETURN m.title as movie , actor.name

How is this block processed? I understand MATCH 1 produces a list of Person nodes who acted in a movie. At this point, the MATCH 2 produces a list of Person nodes who acted in the Movie nodes identified in MATCH 1.

Now when the WHERE is applied to MATCH 2, how is does the condition work on the nodes identified in MATCH 2? I do not see a clear connection between them.

In the OPTIONAL MATCH case, it is a little more intuitive since the WHERE is directly placed after the MATCH statement to which it applies. (at least in the examples I have come across).

1 ACCEPTED SOLUTION
Neo4j

Hello @poornima ,

The Cypher query processor does parse the query to apply the WHERE clause to the first MATCH clause. The only time that the placement of the WHERE clause is significant is when an OPTIONAL MATCH is specified.

If you were to profile the above query vs:
MATCH (valKilmer:Person {name: 'Val Kilmer'})-[:ACTED_IN]->(m:Movie)
MATCH (actor:Person)-[:ACTED_IN]->(m)
RETURN m.title as movie , actor.name

You would see that they are identical in execution.

I will let the documentation team know that the docs should be modified.

Elaine

2 REPLIES 2
Neo4j

Hello @poornima ,

The Cypher query processor does parse the query to apply the WHERE clause to the first MATCH clause. The only time that the placement of the WHERE clause is significant is when an OPTIONAL MATCH is specified.

If you were to profile the above query vs:
MATCH (valKilmer:Person {name: 'Val Kilmer'})-[:ACTED_IN]->(m:Movie)
MATCH (actor:Person)-[:ACTED_IN]->(m)
RETURN m.title as movie , actor.name

You would see that they are identical in execution.

I will let the documentation team know that the docs should be modified.

Elaine

Node Clone

@elaine.rosenberg Thank you, it's clear now.

Nodes 2022

NODES 2022, Neo4j Online Education Summit

All the sessions of the conference are now available online

Neo4j Resources