如何解决Cypher类型不匹配并获取两点间最短巴士行程时间?
解决Cypher多段关系路径的最短行程时间查询问题
报错原因
你使用[c:bus*]匹配的是从Graz到Bregenz的所有巴士路径,这里的c是关系列表(并非单个关系)。直接访问c.fahrzeit会触发类型不匹配,因为列表没有fahrzeit属性,只有单个bus关系才具备该属性。
正确查询语句
要获取最短行程时间,需要先计算每条路径的总行程时长,再从中筛选最小值。可以用reduce函数累加路径中各段关系的fahrzeit,结合min()函数得到结果:
MATCH (g:city {name:"Graz"})-[c:bus*]->(b:city {name:"Bregenz"}) WITH reduce(total = 0, rel in c | total + rel.fahrzeit) AS totalFahrzeit RETURN min(totalFahrzeit) AS shortestTripTime
语句说明
reduce(total = 0, rel in c | total + rel.fahrzeit):遍历当前路径中的每个bus关系,将每段的fahrzeit累加,得到整条路径的总行程时间。min(totalFahrzeit):从所有路径的总时间中提取最小值,即为从Graz到Bregenz的最短巴士行程时间。
如果需要同时查看最短时间对应的路径,可以使用以下语句:
MATCH path = (g:city {name:"Graz"})-[c:bus*]->(b:city {name:"Bregenz"}) WITH path, reduce(total = 0, rel in relationships(path) | total + rel.fahrzeit) AS totalFahrzeit ORDER BY totalFahrzeit ASC LIMIT 1 RETURN path, totalFahrzeit AS shortestTripTime
内容的提问来源于stack exchange,提问作者To08bi
相关产品推荐
相关产品推荐

