neo4j - 与 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
解决方案
[更新]
您的聚合同时使用n
和s
作为分组键,而不仅仅是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
推荐阅读
- django - Django Superuser 无法更改用户权限 - 将用户类型更改为人员
- javascript - 是否可以将异步等待与未在反应中标记为异步的常规功能一起使用?
- go - 如何添加多个包含不同值的同名标头
- android - 如何将 Android 和网站上的 Vimeo 与特定用户访问权限集成
- javascript - Inputpicker 设置值后处理过滤器
- gitlab - gitlab-ci.yml 中的 `only: -master` 匹配什么?
- android - 如何修复颤振小部件闪烁?
- r - 在 R 中创建的 Shapefile 未在 ArcGIS 中显示
- c++ - 在 Test_F 之外调用 Expect_Call
- flutter - 在 Flutter 中滚动时如何为 SingleChildScrollView 使用平滑动画?