问题
Follow up question on This question
I now need to create the relationship between a station and a neighborhood (LOCATED_IN). The first query successfully returns only 1 row per station (1 combination). The second query where I want to create the relationship, creates too much relationships.
MATCH (n:Neighborhood),(s:Station)
WITH n, s, distance(n.centerLocation, s.point) AS dist
ORDER BY dist
RETURN s.stationId, COLLECT(n)[0].name AS name, COLLECT(dist)[0] AS shortest
ORDER BY s.stationId
Query 2:
MATCH (n:Neighborhood),(s:Station)
WITH n, s, distance(n.centerLocation, s.point) AS dist
ORDER BY dist
CREATE (s)-[r:LOCATED_IN]->(nbh)
RETURN s.stationId, COLLECT(n)[0] AS nbh, COLLECT(dist)[0] AS shortest
ORDER BY s.stationId
Query 3:
MATCH (n:Neighborhood),(s:Station)
WITH n, s, distance(n.centerLocation, s.point) AS dist
ORDER BY dist
CREATE (s)-[r:LOCATED_IN]->(n)
RETURN s.stationId, COLLECT(n)[0] AS nbh, COLLECT(dist)[0] AS shortest
ORDER BY s.stationId
After query 2: Stations (blue nodes) are connected to multiple nodes that do not represent neighborhood nodes. They only have an ID.
After query 3: Stations (blue nodes) are connected to multiple neighborhoods nodes. It should only be one neighborhood per station.
How should I write my query to have 1 neighborhood per station?
回答1:
Query 2 is flawed because the CREATE
is using an unbound nbh
variable.
For Query 3, you need to create a relationship from each station to just the single nearest neighborhood. For example:
MATCH (n:Neighborhood), (s:Station)
WITH n, s, distance(n.centerLocation, s.point) AS dist
ORDER BY dist
WITH s, COLLECT(dist)[0] AS shortest, COLLECT(n)[0] AS nbh
CREATE (s)-[:LOCATED_IN]->(nbh)
RETURN s.stationId, nbh, shortest
ORDER BY s.stationId
来源:https://stackoverflow.com/questions/58421117/create-relationship-after-matching-with-aggregate-and-multiple-order-by-clauses