Neo4j - 根据关系属性查找两个节点之间的最短路径

我想弄清楚是否有某种方法可以根据关系总和获得两个节点之间的最短距离,给出这个例子: neo4j image example

上图代码:

CREATE (some_point_1:Point {title:'Some Point 1'})
CREATE (some_point_2:Point {title:'Some Point 2'})
CREATE (some_point_3:Point {title:'Some Point 3'})
CREATE (some_point_4:Point {title:'Some Point 4'})
CREATE (some_point_5:Point {title:'Some Point 5'})
CREATE (some_point_6:Point {title:'Some Point 6'})

CREATE (some_point_1)-[:distance {value:100}]->(some_point_2)
CREATE (some_point_2)-[:distance {value:150}]->(some_point_4)
CREATE (some_point_1)-[:distance {value:200}]->(some_point_3)
CREATE (some_point_3)-[:distance {value:300}]->(some_point_4)
CREATE (some_point_2)-[:distance {value:500}]->(some_point_5)
CREATE (some_point_4)-[:distance {value:300}]->(some_point_5)
CREATE (some_point_5)-[:distance {value:300}]->(some_point_6)
CREATE (some_point_6)-[:distance {value:300}]->(some_point_1)

在此示例中,最短路径应为: some_point_1 > some_point_2 > some_point_4 > some_point_5 (100+150+300 = 550)

Cypher 可以实现这样的功能吗?

最佳答案

Cypher 中的shortestPath 函数不考虑关系属性的累积,因此:

MATCH (start:Point {title: 'Some Point 1'}), (end:Point {title: 'Some Point 5'})
MATCH p=shortestPath((start)-[:distance*]->(end))
RETURN p

会根据路径中的关系数找到从startend 的最短路径。

你可以减少距离的总和:

MATCH (start:Point {title: 'Some Point 1'}), (end:Point {title: 'Some Point 5'})
MATCH p=(start)-[:distance*]->(end)
WITH p,reduce(s = 0, r IN rels(p) | s + r.value) AS dist
RETURN p, dist ORDER BY dist DESC

但这里的问题是您需要计算从startend 的所有路径的总距离。为了提高效率,您需要使用像 Dijkstra's algorithm 这样的图形搜索算法。或 A*,两者都在 Neo4j's Java API 中实现.

在 Neo4j 3.0 中,这些算法通过 APOC procedure library 在 Cypher 中公开。 .安装 APOC 后,您可以从 Cypher 调用该过程:

MATCH (start:Point {title: 'Some Point 1'}), (end:Point {title: 'Some Point 5'})
CALL apoc.algo.dijkstra(start, end, 'distance', 'value') YIELD path, weight
RETURN path, weight

https://stackoverflow.com/questions/38237237/

相关文章:

google-apps-script - 可以在谷歌脚本中设置一个标题

apache-camel - 如何在 apache camel 中全局设置交换属性

r - 如何使用来自多个其他列的所有非 NA 值创建新列?

javascript - 元素 innerHTML 摆脱事件监听器

git - 是否可以轻松地将所有提交从一个分支移动到另一个分支作为一个提交?

php - woocommerce rest API 每次调用仅提供 10 个订单

types - Julia 中的大宽度整数?

regex - 如何在 Chrome Dev Tools 中过滤没有扩展的 XHR 请求?

ruby-on-rails - Rails 加入或包含有条件的 belongs_to

r - 如何在 R 中绘制阶乘函数