Yi Doe
Yi Doe

Reputation: 162

Neo4j, consequetive MATCH path queries

I was trying to write a Cypher query with multiple matches in order to get multiple paths

Query

MATCH (a:A) --> (b:B) where b.uid="asdfas"
MATCH path = (a) -> (leaf) with collect(path) as paths
MATCH another_path = (b) -> (leaf) with collect(another_path) as paths_2

RETURN paths, paths_2

Result

Neo.ClientError.Statement.SyntaxError: Variable `paths` not defined 
"RETURN paths, paths_2"

The return clause forgets about the path

Unlike above, if the MATCH only results in Nodes rather than list of paths

MATCH (a:A) --> (b:B) where b.uid="asdfas"
MATCH path = (a) -> (leaf) with collect(path) as paths
MATCH (b) --> (c:C) 

RETURN paths, c

The above query executes perfectly.

Upvotes: 0

Views: 81

Answers (2)

cybersam
cybersam

Reputation: 67044

A WITH clause causes all existing variables to become unbound except for the variables the WITH clause passes onwards.

The first WITH must pass b, so that the following MATCH can use it. And the second WITH must pass paths so that it can be returned:

MATCH (a:A)-->(b:B) WHERE b.uid="asdfas"
MATCH path = (a)->()
WITH b, COLLECT(path) AS paths
MATCH another_path = (b)->()
WITH paths, COLLECT(another_path) AS paths_2
RETURN paths, paths_2

Even better, your second WITH is not actually needed:

MATCH (a:A)-->(b:B) WHERE b.uid="asdfas"
MATCH path = (a)->()
WITH b, COLLECT(path) AS paths
MATCH another_path = (b)->()
RETURN paths, COLLECT(another_path) AS paths_2

Upvotes: 2

Marcus
Marcus

Reputation: 3646

In your first query, you need to add paths to your final with statement for it to be available to the RETURN statement.

MATCH another_path = (b) -> (leaf) with collect(another_path) as paths_2, paths

Personally, I like to put WITH (and WHERE) statements on separate lines to make these things potentially more clear as to what is being passed on

MATCH (a:A) --> (b:B) 
WHERE b.uid="asdfas"

MATCH path = (a) -> (leaf) 
WITH collect(path) as paths

MATCH another_path = (b) -> (leaf) 
WITH collect(another_path) as paths_2, paths

RETURN paths, paths_2

Upvotes: 1

Related Questions