问题
I have three Person nodes with various relationships. Each node has a latitude and longitude.
First, I find the combinations of pairs of nodes:
MATCH (p1: Person)-[]->(p2: Person)
RETURN p1.name, p2.name
My output is correct:
Next, I attempt to find the distances between the pairs of nodes:
MATCH (p1:Person)-[]->(p2:Person)
WITH point({longitude: p1.longitude, latitude: p1.latitude}) AS p1Point,
point({longitude: p2.longitude, latitude: p2.latitude}) AS p2Point
RETURN (distance(p1Point, p2Point)) AS distance
My output is here:
Finally, I want to put it all together. I want to list the names of each node pair and the associated distance between them:
MATCH (p1:Person)-[]->(p2:Person)
WITH point({longitude: p1.longitude, latitude: p1.latitude}) AS p1Point,
point({longitude: p2.longitude, latitude: p2.latitude}) AS p2Point
RETURN p1.name, p2.name, (distance(p1Point, p2Point)) AS distance
I get an error that p1 is not defined.
What is the problem here? There is similar syntax described here: https://neo4j.com/docs/graph-algorithms/current/labs-algorithms/all-pairs-shortest-path/
回答1:
The WITH
clause unbinds all variables except for the ones it carries forward.
This should work:
MATCH (p1:Person)-->(p2:Person)
WITH p1, p2,
point({longitude: p1.longitude, latitude: p1.latitude}) AS p1Point,
point({longitude: p2.longitude, latitude: p2.latitude}) AS p2Point
RETURN p1.name, p2.name, distance(p1Point, p2Point) AS distance
This should also work (since WITH
is not really needed):
MATCH (p1:Person)-->(p2:Person)
RETURN p1.name, p2.name,
distance(
point({longitude: p1.longitude, latitude: p1.latitude}),
point({longitude: p2.longitude, latitude: p2.latitude})) AS distance
[UPDATED]
By the way, with an always-bidirectional relationship like RELATED_TO
, you should just use a single undirected relationship instead of two directed relationships pointing in opposite directions. Note, though, that the CREATE
clause only supports creating directed relationships, so just pick any arbitrary direction -- it does not matter which. Later, when you do a search, just use an undirected search (like MATCH (p1:Person)--(p2:Person) ...
). Also, you should look into whether you should use MERGE instead, since it does allow an undirected relationship pattern.
来源:https://stackoverflow.com/questions/60643117/neo4j-variable-alias-not-recognized