chinghp
chinghp

Reputation: 117

Neo4j shortestPath reduce function return null

I am trying to use the ShortestPath function in Neo4j.

The route would pass through different nodes which have a LinkLength value. The value in the "reduce" part should be minimized for the shortest LinkLength between 2 Nodes.

Question: Neo4j could find a route as the shortest path solution. Surprisingly, Neo4j says the value of the reduce function is null. What's the error?

MATCH p = (n1:Node)-[:Connects*]->(n2:Node)
WHERE n1.myid = 'M32 J3' AND n2.myid = 'M32 J1'
RETURN p AS shortestPath,
reduce(distance=0.0, n in nodes(p) | case n.LinkLength when NOT NULL then
distance+toFloat(n.LinkLength) end)
LIMIT 1;

Upvotes: 0

Views: 549

Answers (1)

Stefan Armbruster
Stefan Armbruster

Reputation: 39915

Your case statement does not have an else part. Not 100% sure, but I guess in this case you'll return null for the accumulator value - null + 1 == null.

The right way to takle that is by filtering out nodes with null values first and apply reduce afterwards:

MATCH p = (n1:Node)-[:Connects*]->(n2:Node)
WHERE n1.myid = 'M32 J3' AND n2.myid = 'M32 J1'
RETURN p AS shortestPath,
reduce(distance=0.0, n in [x in nodes(p) WHERE n.LinkLength IS NOT NULL] |
   distance+toFloat(n.LinkLength))
LIMIT 1;

Further I guess you basically want to calculate a shortest weighted path. Your statement just gets the weight of the first path found. For doing weighted shortest paths efficiently take a look at https://neo4j-contrib.github.io/neo4j-apoc-procedures/#_graph_algorithms_work_in_progress. (remember: apoc requires Neo4j >= 3.0).

Upvotes: 0

Related Questions