繁体   English   中英

neo4j中通过航路点的2个节点之间的最短路径

[英]shortest path between 2 nodes through waypoints in neo4j

我在neo4j中有一个图,其中一个节点代表一个城市,一个关系代表连接城市的道路。 关系经过加权,并具有称为“距离”的属性。 我想找到两个城市A和B之间的最短路径(最小加权路径)。使用Dijkstra的算法很容易做到这一点。 棘手的部分是,我有一组从A到B的路径将要覆盖的城市。换句话说,从A到B的路径应覆盖所有路标,顺序无关紧要。 诸如提供航点的来源,目的地和列表并进行优化:在Google API中为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),但不确定如何访问所有航路点。

提前致谢!!

尝试使用ANY而不是ALL

来自neo4j文档

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM