'Cypher/Neo4j – Storing bracketed variable in global scope
The following cypher query fails at the last line because p2 is only defined within scope after EXISTS, but is there a way to bring it out of that scope somehow (e.g. set it to a global variable) and return it?
MATCH (p:Person)
WHERE EXISTS {
MATCH (p{name: 'José'})<-[:CHILD_OF]-(p2:Person)
WHERE p2.name IN ['Roberto', 'Gustavo']
}
RETURN (p), (p2) // fails
P.S.: I know that the easiest solution is to just NOT use the scope in the first place, my question is whether the functionality I'm looking for exists.
Solution 1:[1]
Existential queries used in EXISTS cannot return values. You need to use CALL if you want to do post processing of a sub query's results.
It looks like you want to try:
MATCH (p:Person)
CALL {
WITH p
MATCH (p{name: 'José'})<-[:CHILD_OF]-(p2:Person)
WHERE p2.name IN ['Roberto', 'Gustavo']
RETURN p2
}
RETURN p, p2
The WITH in the CALL makes the p from the outer query available to the inner query.
Solution 2:[2]
I would have done this:
MATCH (p:Person)<-[:CHILD_OF]-(p2:Person)
WHERE p.name = 'Josè'
AND p2.name IN ['Roberto', 'Gustavo']
RETURN p,p2
Solution 3:[3]
You can remove the where exists clause and directly do the query on Jose and his parents.
MATCH (p: Person{name: 'José'})<-[:CHILD_OF]-(p2:Person)
WHERE p2.name IN ['Roberto', 'Gustavo']
RETURN p, p2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marj |
| Solution 2 | RosarioB |
| Solution 3 | jose_bacoy |
