Neo4j: Shortest Path with Cost Function depending on two Consecutive Relations in Path

廉价感情. 提交于 2019-12-12 04:58:45

问题


Say I have a graph with nodes representing cities and and relations representing possible connections between cities. A connection has a departure and an arrival time. I want to find the shortest path between cities A and B and the cost function is the total travel time. The travel time is the sum of waiting times between connections and connection times.

I'm using the Java API and I have tried using the Dijkstra algorithm using GraphAlgoFactory.dijkstra(expander, costEvaluator). My main problem seems to be, that the CostEvaluator interface only receives the current relation and not the complete path. This way I can compute the connection duration but not the waiting time.

Is there something I can do to adapt the existing algorithm or do I have to reimplement Dijkstra?


回答1:


The total cost of a path will be the sum of the getCost() returned values of every evaluation of the given relationship, so just define how the cost should be evaluated on the relationship level, what the total cost will be is evaluated by the algorithm itself.

On the other hand, you can do it with Cypher, assuming the waiting time is the difference between departure_time and arrival_time :

MATCH p=(a:City {name:"NY"})-[r:CONNECTS*..10]->(b:City {name:"LA"})
WITH p, reduce(
  cost=0, x IN rels(p) | cost + (x.departure_time - x.arrival_time) 
) as cost
RETURN p, cost
ORDER BY cost ASC
LIMIT 1


来源:https://stackoverflow.com/questions/39492944/neo4j-shortest-path-with-cost-function-depending-on-two-consecutive-relations-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!