neo4j shortest with connector node and multiple options

128 views Asked by At

I have Cities, Roads and Transporters in my database. A Road is connected with a From and To relationship to two (different) Cities. Each road has also a property distance (in kilometers). Multiple Transporters could have a relationship to Roads. Every Transporter has a price (per kilometer).

Now my question. I want the cheapest option to get a packet from city A to B. There could be a direct road or else we have to go via other cities and transporters. And I want explicitly use the Dijkstra algorithm for this.

Can this query be done in Cypher? And if not, how can it be done using the Neo4J Java API?

1

There are 1 answers

1
Christophe Willemsen On

Based on your sample dataset, I think there is a modelisation problem that makes maybe things difficult, certainly for matching on directed relationships.

However this is already how you can find the lowest cost path :

MATCH (a:City { name:'CityA' }),(d:City { name:'CityD' })
MATCH p=(a)-[*]-(d)
WITH p, filter(x IN nodes(p) 
               WHERE 'Road' IN labels(x)) AS roads
WITH p, reduce(dist = 0, x IN roads | dist + x.distance) AS totalDistance
RETURN p, totalDistance
ORDER BY totalDistance
LIMIT 5