Search code examples
neo4jneo4j-apoc

Shortest path on a topological graph with default weight


Using neo4j (with APOC 5.7), I'm trying to find the shortest path on a topological graph (no location on the nodes), where the weight of each step is 1 by default. I don't want to limit the number of steps for the path, only the relationship type.

The documentation is very flat:

apoc.algo.dijkstra requires a weight on the relationship

apoc.algo.dijkstraWithDefaultWeight throws: There is no procedure with the name apoc.algo.dijkstraWithDefaultWeight

apoc.algo.aStar and apoc.algo.aStarWithPoint require points location or lat and long

apoc.algo.allSimplePaths requires maxNodes and is a full graph search...

For example, for the graph:

CREATE (b:City {name:'Berlin'})
CREATE (m:City {name:'München'})
CREATE (f:City {name:'Frankfurt'})
CREATE (h:City {name:'Hamburg'})
MERGE (b)-[:DIRECT]-(h)
MERGE (b)-[:DIRECT]-(m)
MERGE (b)-[:DIRECT]-(f)
MERGE (f)-[:DIRECT]-(m)
MERGE (f)-[:DIRECT]-(h)

I would like the get something like:

╒════════╤══════════════════════════════════════════════════════════════════════╕
│weight  │path                                                                  │
╞════════╪══════════════════════════════════════════════════════════════════════╡
│2.0     │(:City {name: "München"})<-[:DIRECT]-(:City {name: "Frankfurt"})-     |
│        │[:DIRECT]->(:City {name: "Hamburg"})                                  │       
└────────┴──────────────────────────────────────────────────────────────────────┘

Currently, the simplest option I see is to use apoc.algo.dijkstra and add a weight property with a value 1 on each relationship - which is absurd.

Any advice?


Solution

  • If you don't care about the weight you may not have to use APOC at all, but instead the built-in Cypher shortestPath function:

    MATCH path=shortestPath((:City {name: 'München'})-[d:DIRECT*]-(:City {name: 'Hamburg'})) RETURN size(d) AS weight, path
    

    which gives this result

    ╒══════╤══════════════════════════════════════════════════════════════════════╕
    │weight│path                                                                  │
    ╞══════╪══════════════════════════════════════════════════════════════════════╡
    │2     │(:City {name: "München"})<-[:DIRECT]-(:City {name: "Frankfurt"})-[:DIR│
    │      │ECT]->(:City {name: "Hamburg"})                                       │
    └──────┴──────────────────────────────────────────────────────────────────────┘