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.

Calculate the sum of values of a tree

I have a binary tree representation in the database:
Each node has two outgoing connections, LEFT and RIGHT.

The following query fetches the tree up to a depth of 15.

MATCH path = (d1:Distributor)-[*0..15]->(d2:Distributor)
WHERE d1.dist_id = '1'
RETURN d2, path, nodes(path) as nodes, relationships(path) as rels

Each node will also consist of a property called count, with different values.

However, what I am trying to do is. for a given node, calculate the sum of all count properties of all the child nodes in the tree below him, recursively.

I tried with the following, but evidently, it is only considering the immediate child node.

MATCH path = (d1:Distributor)-[:LEFT|RIGHT]->(d2:Distributor)
WHERE d1.dist_id = '1'
RETURN sum(d2.count)

Is there any way to achieve this?

2 REPLIES 2

After playing around on my system, it looks like you just need to change your relationship to [:LEFT|RIGHT*] to get it to go down through the nodes.

Solved the issue in the following way.

MATCH (d1:Distributor)-[*]->(d2:Distributor)
with d1, sum (d2.counter) AS tot_counter 
RETURN d1.cid, tot_counter