首页 > 解决方案 > 动态值的 Neo4j 聚合

问题描述

我正在研究 neo4j 的 APOC 程序。我无法获得以下查询返回的所有节点的平均距离。

match(n:Company)  
WHERE NOT (n)-[:refersTo]->() and n.name starts with "google" 
with n as company, apoc.text.distance('google', n.name_lower) as distance  
return company.name, distance, avg(distance)

distance 和 avg(distance) 的值始终相同。下面是结果样本的图片。

在此处输入图像描述

编辑 1:尝试了建议的查询:

match(n:Company)  
WHERE NOT (n)-[:refersTo]->() and n.name_lower starts with "google" 
with n as company, apoc.text.distance('google', n.name_lower) as distance  
with company, collect(distance) as distances, avg(distance) as distAvg
unwind distances as distance
return company.name as name, distance, distAvg

得到相同的结果。

在此处输入图像描述

标签: neo4jcypher

解决方案


此查询将返回名称/距离对的集合以及所有距离的平均值:

MATCH (n:Company)  
WHERE NOT (n)-[:refersTo]->() AND n.name_lower starts with "google"
WITH n.name AS name, apoc.text.distance('google', n.name_lower) AS distance
RETURN COLLECT({name: name, distance: distance}) as data, AVG(distance) as distAvg;

这是一个示例结果:

╒══════════════════════════════════════════════════════════════════════╤═════════╕
│"data"                                                                │"distAvg"│
╞══════════════════════════════════════════════════════════════════════╪═════════╡
│[{"name":"Google Inc.","distance":5},{"name":"Google Max","distance":4│4.5      │
│}]                                                                    │         │
└──────────────────────────────────────────────────────────────────────┴─────────┘

推荐阅读