首页 > 解决方案 > 与 Cypher 中的聚合函数 min() 匹配最短距离

问题描述

我有 Station 节点和 Neighborhood 节点。它们都具有point空间数据类型的位置属性。

我需要在节点之间创建关系(一个 Station 属于最近的邻居)。因此,我应该每个站只得到一排。但是,我的查询结果返回了所有组合。

MATCH (n:Neighborhood),(s:Station)
WITH n, s, min(distance(n.centerLocation, s.point)) AS shortest
WHERE distance(n.centerLocation, s.point) = shortest
RETURN s.stationId, n.name, shortest
ORDER BY s.stationId

标签: neo4jcypher

解决方案


[更新]

您的聚合同时使用ns作为分组键,而不仅仅是s.

这应该适合你:

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

请注意,如果您有很多社区和车站,此查询将会很慢(并且可能会耗尽内存),因为它必须评估每个可能的社区和车站组合。

作为一种潜在的解决方法,您可以创建数量相对较少的Region节点并将每个节点与Station特定Neighborhood区域相关联。完成后,您可以减少需要评估的组合数量。例如:

MATCH (n:Neighborhood)-[:IN_REGION]->()<-[:IN_REGION]-(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

为了获得更好的结果,如果与这些区域中心点的距离仅相差某个阈值,您还可以将Station或放入多个区域。Neighborhood


推荐阅读