2017-08-22 75 views
0

我在neo4j中有一个图表,其中一个节点代表一个城市,一条关系代表连接城市的道路。这些关系是加权的,并且有一个称为“距离”的属性。 我想找到两个城市A和B之间最短的(最小加权的路径)。这很容易使用Dijkstra算法完成。棘手的部分是我有一组城市,这些城市将被覆盖在从A到B的路径中。换句话说,从A到B的路径应该覆盖所有的路标,顺序无关紧要。 就像在Google API中提供路线点的来源,目的地和列表并优化:true一样。 我曾尝试使用这种Cypher支架与下面的查询 -neo4j中通过航点的2个节点之间的最短路径

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遍历),但不知道如何访问所有的路标。

在此先感谢!

回答

0

尝试使用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 
+0

我想要的路径应该包含所有的点在列表中。我认为“任何”不会解决它。 – mayankgupta565

+0

@ mayankgupta565修改我的答案以确保包含所有路标 –

相关问题