title: How to find all shortest paths efficiently based on the cost in neo4j using cypher
body: <p>How to find all shortest paths efficiently based on the cost in neo4j (3.1.0) using cypher?</p>
  
  <p>My current approach is to use <code>allShortestPaths</code> and then order by</p>
  
  <p><strong>Sample Data</strong></p>
  
  <pre><code>//node with cost
  MERGE (a:A{name:"A"})
  MERGE (b:A{name:"B"})
  MERGE (c:A{name:"C"})
  MERGE (d:A{name:"D"})
  MERGE (ee:A{name:"E"})
  MERGE (a) -[:R{cost:-4}]-&gt; (b)
  MERGE (a) -[:R{cost:-1}]-&gt; (c)
  MERGE (a) -[:R{cost:2}]-&gt; (d)
  MERGE (b) -[:R{cost:5}]-&gt; (ee)
  MERGE (d) -[:R{cost:-2}]-&gt; (ee)
  </code></pre>
  
  <p><strong>Cypher</strong></p>
  
  <pre><code>//list all paths with cost
  MATCH (n1),(n2) ,p=allShortestPaths((n1)-[*..10]-&gt;(n2))
  WITH 
  p,
  reduce(cost=0,x in relationships(p) | cost+x.cost) AS cost ,
  reduce(s="(",x in nodes(p) | s+"-&gt;"+x.name)+")" AS path
  ORDER BY cost DESC, LENGTH(p) DESC
  return path,cost
  </code></pre>
  
  <p><strong>Result</strong></p>
  
  <pre><code>╒═════════════╤══════╕
  │"path"       │"cost"│
  ╞═════════════╪══════╡
  │"(-&gt;B-&gt;E)"   │"5"   │
  ├─────────────┼──────┤
  │"(-&gt;A-&gt;D)"   │"2"   │
  ├─────────────┼──────┤
  │"(-&gt;A-&gt;B-&gt;E)"│"1"   │
  ├─────────────┼──────┤
  │"(-&gt;A-&gt;D-&gt;E)"│"0"   │
  ├─────────────┼──────┤
  │"(-&gt;A-&gt;C)"   │"-1"  │
  ├─────────────┼──────┤
  │"(-&gt;D-&gt;E)"   │"-2"  │
  ├─────────────┼──────┤
  │"(-&gt;A-&gt;B)"   │"-4"  │
  └─────────────┴──────┘
  </code></pre>
  
  <p>See
  <a href="http://console.neo4j.org/?id=lh5lym" rel="nofollow noreferrer">http://console.neo4j.org/?id=lh5lym</a></p>
  
  <p>Execution Plan</p>
  
  <pre><code>Total database accesses: 98
  </code></pre>
  
  <p>is this the correct way to find the shortest path based on cost or if  there is any better/efficient approach (when number of nodes and depth of path increases) ?</p>