The shortestPath
Cypher 中的函数不考虑关系属性的累积,因此:
MATCH (start:Point {title: 'Some Point 1'}), (end:Point {title: 'Some Point 5'})
MATCH p=shortestPath((start)-[:distance*]->(end))
RETURN p
会找到最短路径start
to end
基于路径中的关系数量。
您可以减少距离的总和:
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
但这里的问题是你需要计算所有路径的总距离start
to end
。为了提高效率,您需要使用图搜索算法,例如迪杰斯特拉算法 https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm或 A*,两者均在Neo4j 的 Java API http://neo4j.com/docs/java-reference/current/#tutorials-java-embedded-graph-algo.
在 Neo4j 3.0 中,这些算法通过 Cypher 公开APOC程序库 https://github.com/neo4j-contrib/neo4j-apoc-procedures。安装 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