cancel
Showing results for 
Search instead for 
Did you mean: 

Join the community at Nodes 2022, our free virtual event on November 16 - 17.

Cypher Query - Sum function for lower nodes

pragyasood28
Node Clone

Hi Everyone,

I am facing a challenge calculating the sum of lower nodes in my graph.

Consider the below scenario:

Multiple such paths are present in the graph, and I want to calculate the sum of all the lowest nodes of Storage and store the value of Requirement in the second last node.

My query is this

match p=(a:Production)-[]->(b:Storage)-[]->(c:Storage)-[]->(d:Storage)
with c, sum(d.Requirement) as req
set c.Requirement=req
return c;

So this is giving the correct result for the 1st graph that is 50 is getting stored in c.Requirement property of the first tree, but for the second one 100 is getting stored in c.Requirement, but I want that the value should not get doubled up even if 2 similar paths are there on that tree.

Any suggestions on how this situation can be handled ?

Thank You,
Pragya

1 ACCEPTED SOLUTION

Give this a try, it should also work for longer paths where you may not know the depth:

MATCH (a:Production)-[*]->(secondToLast:Storage)-->(last:Storage)
WHERE NOT (last)-->(:Storage)
WITH DISTINCT secondToLast, last
WITH secondToLast, sum(last.Requirement) as req
SET secondToLast.Requirement = req

View solution in original post

2 REPLIES 2

Joel
Ninja
Ninja

using DISTINCT on the node, should do what you need

Give this a try, it should also work for longer paths where you may not know the depth:

MATCH (a:Production)-[*]->(secondToLast:Storage)-->(last:Storage)
WHERE NOT (last)-->(:Storage)
WITH DISTINCT secondToLast, last
WITH secondToLast, sum(last.Requirement) as req
SET secondToLast.Requirement = req