【问题标题】:shortest path between 2 nodes through waypoints in neo4j2个节点之间通过neo4j中路点的最短路径
【发布时间】:2017-08-22 02:34:27
【问题描述】:

我在 neo4j 中有一个图表,其中一个节点代表一个城市,一个关系代表连接城市的道路。这些关系是加权的,并具有称为“距离”的属性。 我想找到两个城市 A 和 B 之间的最短(最小加权路径)。这很容易使用 Dijkstra 算法完成。棘手的部分是我有一组城市要覆盖在从 A 到 B 的路径中。换句话说,从 A 到 B 的路径应该覆盖所有航路点,顺序无关紧要。 类似于在 Google API 中提供来源、目的地和航点列表以及 optimize:true 之类的东西。 我已经通过以下查询使用 Cypher 进行了尝试-

match(s:City{ID:"A"})
match(f:City{ID:"B"})
match (n:City) where n.name in ['City1','City2','City3','City4']
with collect(n) as wps 
match path=allshortestPaths((s)-[:ROADWAY*..9]->(f))
where ALL ( n in wps WHERE n in nodes(path) ) with path, 
reduce(d=0, rel IN relationships(path)| d+rel.displacement) as             
totaldistance,Extract (n in nodes(path)| n.name) as cities 
return cities, totaldistance, tofloat(totaldistance) as TD order by 
totaldistance

但这没有用。也许是因为路径没有通过所有的航路点。 我也在尝试使用 A* 或 Dijkstra(使用 Neo4j Traversal),但不确定如何访问所有航点。

提前致谢!!

【问题讨论】:

    标签: algorithm graph neo4j cypher


    【解决方案1】:

    尝试使用ANY 而不是ALL

    来自neo4j documentation

    All - 测试一个谓词是否适用于该列表的所有元素。

    Any - 测试一个谓词是否适用于至少一个元素 列表。

    match(s:City{ID:"A"})
    match(f:City{ID:"B"})
    match (n:City) where n.name in ['City1','City2','City3','City4']
    with collect(n) as wps 
    match path=allshortestPaths((s)-[:ROADWAY*..9]->(f))
    where ANY ( n in wps WHERE n in nodes(path) ) with path, 
    reduce(d=0, rel IN relationships(path)| d+rel.displacement) as             
    totaldistance,Extract (n in nodes(path)| n.name) as cities 
    return cities, totaldistance, tofloat(totaldistance) as TD order by 
    totaldistance
    

    编辑 - 我们可以通过在 where 子句中组合多个 ANY 来更改它以确保包含所有城市:

    match(s:City{ID:"A"})
    match(f:City{ID:"B"})
    with collect(n) as wps 
    match path=allshortestPaths((s)-[:ROADWAY*..9]->(f))
    where ANY ( n in nodes(wps) WHERE n.name = 'City1' ) AND
          ANY ( n in nodes(wps) WHERE n.name = 'City2) 
    with path, 
    reduce(d=0, rel IN relationships(path)| d+rel.displacement) as             
    totaldistance,Extract (n in nodes(path)| n.name) as cities 
    return cities, totaldistance, tofloat(totaldistance) as TD order by 
    totaldistance
    

    【讨论】:

    • 我希望路径应该包含列表中的所有点。我认为“ANY”不会解决它。
    • @mayankgupta565 修改了我的答案以确保包含所有航点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2016-03-04
    • 1970-01-01
    • 2011-03-08
    • 2017-08-20
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多