bruce_w
bruce_w

Reputation: 21

Cypher (Neo4j), how to sum a given property through a full path

I have been struggling to find a solution to my issue with Cypher.. I am trying to sum a given relationship throughout a path.

For example: 1 --> 2 --> 3 --> 4 I want to calculate for node 1 the sum of Amount property for nodes 1,2 3 and 4. (In that case 3 and 4 are both targets of node 2, which i cant manage to represent here)

My understanding is I need to be using collect() and reduce but I still do not get the right answer. I have the following:

MATCH (n)-[p]->(m)
WITH m,n, collect(m) AS amounts
RETURN n.ID as Source,m.ID as Target,n.Amount, 
REDUCE(total = 0, tot IN amounts | total + tot.Amount) AS totalEUR
ORDER BY total DESC

I get a syntax error, but I am pretty sure even without the syntax error that i will only be summing direct relationships...

Would you guys know if I am on the right path?

Cheers Max

Upvotes: 2

Views: 1900

Answers (1)

Frank Pavageau
Frank Pavageau

Reputation: 11735

You need a variable-length relationship in the query:

MATCH p = (n)-[*]->(m)
RETURN n.ID as Source, m.ID as Target, n.Amount,
       reduce(total = 0, tot IN nodes(p) | total + tot.Amount) AS totalEUR
ORDER BY totalEUR DESC

You can't order by total which is a variable local to the reduce function.

Note that this will return rows for each path, i.e. 1-->2, 1-->2-->3, 1-->2-->3-->4, 2-->3, 2-->3-->4, 3-->4, since you haven't matched on a specific n.

Upvotes: 1

Related Questions