在Neo4j中实现Dijkstra算法

时间:2014-12-07 19:10:55

标签: neo4j cypher

我是Neo4j的新手。有人可以向我解释(请一步一步)我如何实现Dijkstra的算法来找到两个节点之间的最短路径?是否可以使用Cypher简单地完成它?

我已经尝试过shortestPath算法,但速度非常慢:

MATCH (from: Location {LocationName:"x"}), (to: Location {LocationName:"y"}) , path = (from)-[:CONNECTED_TO*1..5]->(to)
RETURN path AS shortestPath, 
    reduce(distance = 0, r in relationships(path)| distance+toInt(r.Distance)) 
AS totalDistance
    ORDER BY totalDistance ASC
    LIMIT 1

我的节点是:具有LocationID和LocationName属性的位置 我的关系是:CONNECTED_TO与属性距离

我有超过6000个关系

请注意上面的代码中我限制为1..5 当我没有定义这个限制时,查询不会给出任何结果(继续执行)

感谢

2 个答案:

答案 0 :(得分:14)

是的,可以使用Cypher或dedicated endpoint Neo4j ReST API。

BTW,来自Cypher Neo4j文档的示例是自我解释:

http://neo4j.com/docs/milestone/query-match.html#_shortest_path

获取两个节点之间的最短路径:

MATCH (from: Location {LocationName:"x"}), (to: Location {LocationName:"y"}) , 
path = shortestPath((from)-[:CONNECTED_TO*]->(to))
RETURN path

如果你想获得所有最短的

MATCH (from: Location {LocationName:"x"}), (to: Location {LocationName:"y"}) , 
paths = allShortestPaths((from)-[:CONNECTED_TO*]->(to))
RETURN paths

如果要按路径的长度(跳数)按降序排序:

MATCH (from: Location {LocationName:"x"}), (to: Location {LocationName:"y"}) , 
paths = allShortestPaths((from)-[:CONNECTED_TO*]->(to))
RETURN paths
ORDER BY length(paths) DESC

如果要获得shortestPath +关系距离属性的总和:

MATCH (from: Location {LocationName:"x"}), (to: Location {LocationName:"y"}) , 
path = shortestPath((from)-[:CONNECTED_TO*]->(to))
WITH REDUCE(dist = 0, rel in rels(path) | dist + rel.distance) AS distance, p
RETURN p, distance

答案 1 :(得分:0)

执行查询的另一种方法:

在neo4j中安装“ APOC” https://neo4j-contrib.github.io/neo4j-apoc-procedures/#utilities

MATCH(开始:节点{name:'First_node_name'}),(结束:节点{name:'end_node_name'}) CALL apoc.algo.dijkstra(start,end,'weight_property',1.0)产量路径,重量 返回路径,重量


P.S。 “ weight_property”这是PropertyName,它必须与您有关系(weight_property = 225454)

返回了两个值:

  1. 路径-这是找到的路径;
  2. 权重-从每个关系中汇总的权重汇总数