cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Cypher Query - Sum function for lower nodes

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

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