我在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)但不确定如何访问所有航路点。
提前致谢!!
答案 0 :(得分:0)
尝试使用ANY
而不是ALL
。
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