Failed to query with multi MATCH and WITH clauses

I have a match query which failed to run on Neo4j

match (b)-[]-() 
with count(*) as middleNodeRelations,b
match (a)-[]->() 
with count(*) as endNodesRelations,a
match(a: html) < -[r1]-(b: html) < -[r2]-(c: html)
where (middleNodeRelations=2) AND (endNodesRelations>1) AND(a.context <> '') AND(b.context='') AND(c.context='')
return a

Firstly, I want to check the number of relations connected with node b, and number of relations connected with node a, and then check whether the node a ,b and c can meat the rules in WHERE clause. But I have the Error:

Neo.ClientError.Statement.SyntaxError: Variable `middleNodeRelations` not defined (line 6, column 8 (offset: 169))
"where (middleNodeRelations=2) AND (endNodesRelations>1) AND(a.context <> '') AND(b.context='') AND(c.context='')"
        ^

I think the reason maybe the first WITH is too far from the WHERE clause. I have spend a lot of time in correcting this query, but still failed.
Any suggestions are welcomed! Thanks ahead!

The with statement defines the set of variables that the NEO4J engine continues to keep track of for the query. Any variable that is not in the list is removed from NEO4J's variable list associated with the query. The second with statement does not list middleNodeRelations, and that is why you get the "middleNodeRelations" is not defined error.

You could potentially add middleNodeRelations to the second with statement to get further.

It strikes me that perhaps the first two match statements are very expensive (in a large database) and I wonder if they are needed at all. I wonder if you could do this with only the the final match statement and use the where clause to ask how many relations there are. I am guessing here but I think perhaps count(r1) and count(r2) could be examined (the relationship variables).

Something like ...

where count(r2)=2 and count(r1) > 1 ... (rest of the where clause)

1 Like

Thanks for your explaination about the Error. That's what I need. The first two match are indeed not necessary, and I change my query into below, and finally it success:

match(a: html) < -[r1]-(b: html) < -[r2]-(c: html)
where  (size((b)-[]-())=2) AND (size((a)-[]->())>1) AND(a.context <> '') AND(b.context='') AND(c.context='')
return a
1 Like