Search code examples
neo4jcypherdijkstra

Using more than once property in Dijkstra algorithm in Neo4j


Is there any way in Cypher I can use the Dijkstra algorithm to calculate minimal weight with more than one property instead of:

CALL apoc.algo.dijkstra(start, end, 'RELATED_TO>', '1_property') 
yield path, weight

to do something like:

  CALL apoc.algo.dijkstra(start, end, 'RELATED_TO>', '1_property+2_property') 
yield path, weight

It doesn't work for me. Do you have suggestions? Cause I want to put into the calculation of the weight the length of the path as an influence on the min weights calculation.


Solution

  • You can take a look at Memgraph, high-performance, in-memory and transactional graph database. openCypher and Bolt compatible. (DISCLAIMER: I'm the co-founder and CTO). Memgraph has built in weighted shortest path feature where the total weight is calculated via user-defined lambda function. Based on this dataset

    CREATE (n1 {id: 1}) CREATE (n2 {id: 2}) CREATE (n3 {id: 3}) CREATE (n4 {id: 4})
    CREATE (n1)-[:E {weight1: 1, weight2: 1}]->(n2)
    CREATE (n1)-[:E {weight1: 2, weight2: 10}]->(n3)
    CREATE (n2)-[:E {weight1: 3, weight2: 100}]->(n4)
    CREATE (n3)-[:E {weight1: 4, weight2: 1}]->(n4);
    

    the relevant Memgraph's query is

    MATCH (a {id: 1})-[
              edges *wShortest (e, n | e.weight1 + e.weight2) total_weight
          ]-(b {id: 4})
    RETURN startNode(head(edges)).id +
           reduce(acc = "", edge IN edges | acc + " -> " + endNode(edge).id) AS hops,
           total_weight;
    

    with the following result.

    | hops      | total_weight |
    |-----------|--------------|
    |1 -> 3 -> 4| 17.0         |