SAB
SAB

Reputation: 175

sum a node attribute along all paths in neo4j

I am trying to calculate the shortest path between two nodes but taking into account a length value stored in an attribute of some of the nodes.

match (origin:type1 {t1id:"start"}),
    (dest:type2 {t2id:"end"}),
    path= (origin)<-[:JOINS]-()-[:JOINS*..10]-()<-[:PARKING]-(dest)
    with extract(n in NODES(path) | n._length) as x
    return x

There are three types of nodes and a path follows:

(type1)-[:JOINS]-(type2)-[:JOINS]-(type1)-[:JOINS]-(type2)-...<-[:PARK]-(type3) 

The query above gives a list of paths (below) but I can't find a way to sum the values along the path to give a total length of each individual path. The null values are relating to type2 nodes which do not have a length value.

x
[8.06, null, 34.25, null, 46.52, null, 37.38, null, 44.2, null]
[8.06, null, 34.25, null, 32.41, null, 31.3, null, 19, null, 44.2, null]
[8.06, null, 34.25, null, 14.63, null, 44.2, null]
[8.06, null, 32.41, null, 46.52, null, 37.38, null, 44.2, null]
[8.06, null, 32.41, null, 34.25, null, 31.3, null, 19, null, 44.2, null]
[8.06, null, 32.41, null, 14.63, null, 44.2, null]
[8.06, null, 31.3, null, 35.86, null, 57.93, null, 55.35, null, 44.2, null]
[8.06, null, 31.3, null, 19, null, 44.2, null]

When i use unwind it just provides a list of all the lengths and not separated by path (below)

y
8.06
null
34.25
null
46.52
null
37.38
null
44.2
null
8.06
null
34.25
null
...etc

Any help or advice would be much appreciated.

Upvotes: 2

Views: 621

Answers (1)

stdob--
stdob--

Reputation: 29167

You need reduce and case and by path aggregation:

match  (origin:type1 {t1id:"start"}),
       (dest:type2 {t2id:"end"})
with   origin, dest
match  path= (origin)<-[:JOINS]-()-[:JOINS*..10]-()<-[:PARKING]-(dest)
return path,
       reduce(acc=0, n in nodes(path) |
              acc + case when n._length is null then 0 else n._length end
       ) as pathLength

Upvotes: 2

Related Questions