Neo4j version 5.12(I am working on the graph academy )
This Cypher query works.
WITH 'toy story' AS mt, 'Tom Hanks' AS actorName
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WITH m, toLower(m.title) AS movieTitle, actorName
WHERE p.name = actorName AND movieTitle CONTAINS mt
RETURN m.title AS movies, movieTitle, actorName
But this below one does not.
WITH 'toy story' AS mt, 'Tom Hanks' AS actorName
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WITH m, toLower(m.title) AS movieTitle
WHERE p.name = actorName AND movieTitle CONTAINS mt
RETURN m.title AS movies, movieTitle, actorName
I know it does not because I tested it and got the below error,
Variable actorName not defined (line 5, column 39 (offset: 218))
"RETURN m.title AS movies, movieTitle, actorName"
But the same variable is available to the WHERE clause.
Essentially implying that actorName to be available to RETURN it must be declared in the second WITH but it is not needed to be declared to be used in the WHERE clause.
I want to understand WHY that is the case. Would appreciate if someone could guide me to some reference material that talks about "variable scope" in Cypher.
It is important to note that WITH affects variables in scope. Any variables
not included in the WITH clause are not carried over to the rest of the
query. The wildcard * can be used to include all variables that are
currently in scope.
Oddly, your value of 'p' is not passed through in either query and first one still parses without it. The second query passes parsing if you remove the 'actorName' variable from the 'return' clause and leave it in the 'where' clause. This seems inconsistent with my understanding. Both 'p' and 'actorName' are not in the preceding 'with', but there is no parsing error on the subsequent 'where' clause.
The plan shows the values are not projected, but then uses them in the subsequent filter operation.
Thanks for the response.
That is exactly my contention and point of confusion. The variable actorName is available to WHERE clause but not the RETURN clause in the 2nd query. Trying to understand how and why this is possible.
Thanks for the response.
And yes good catch. There seems to be an anomaly(or just lack of clarity) about how the query parses, creates the tokens, the data structure it is using to place these tokens to later pick up and process.