如何在Neo4j中查询两节点间所有路径及以0开头的累计权重成本
Neo4j 路径累计成本查询解决方案
你可以通过以下两种写法实现以0开头的累计成本序列输出:
原生Cypher写法(兼容所有版本,无需额外安装插件)
MATCH p=(o)-[r*]->(x) WHERE ID(o) = 13 AND ID(x) = 14 WITH nodes(p) AS path_nodes, [y IN r | y.cost] AS step_costs WITH path_nodes, step_costs, [i IN range(0, size(path_nodes)-1) | CASE WHEN i = 0 THEN 0 ELSE reduce(total = 0, idx IN range(0, i-1) | total + step_costs[idx]) END ] AS cumulative_cost RETURN [n IN path_nodes | id(n)] AS list_path, cumulative_cost
逻辑说明:
- 路径的节点数量永远比边的数量多1,第一个节点对应的累计成本固定为0
- 第n个节点(索引从1开始)的累计成本等于前n条边的成本总和,通过
reduce函数逐次累加实现
APOC简化写法(需提前安装APOC函数库)
如果你使用的环境已经安装了APOC插件,可以直接调用封装好的累加函数,写法更简洁:
MATCH p=(o)-[r*]->(x) WHERE ID(o) = 13 AND ID(x) = 14 WITH [n IN nodes(p) | id(n)] AS list_path, [y IN r | y.cost] AS step_costs RETURN list_path, [0] + apoc.coll.accumulate(step_costs) AS cumulative_cost
如果你要适配之前按节点名称查询的测试场景,只需要修改MATCH和WHERE条件即可:
MATCH p=(o:Location {name:"A"})-[r:ROAD*]->(x:Location {name:"B"}) WITH [n IN nodes(p) | n.name] AS list_path, [y IN r | y.cost] AS step_costs WITH list_path, step_costs, [i IN range(0, size(list_path)-1) | CASE WHEN i = 0 THEN 0 ELSE reduce(total = 0, idx IN range(0, i-1) | total + step_costs[idx]) END ] AS cumulative_cost RETURN list_path, cumulative_cost
运行后将直接输出你预期的格式:
| list_path | cumulative_cost |
|---|---|
| ["A","C","J","H","B"] | [0,50,90,120,170] |
| ["A","B"] | [0,50] |
内容的提问来源于stack exchange,提问作者Karippery
相关产品推荐
相关产品推荐

