Benoit D.
Benoit D.

Reputation: 43

sum of property array

I'm setting a property as an array of integer:

MATCH (n:Node) where id(n) = 1 set n.prop = [1,2,3,4]

and then trying to call the sum of the property:

MATCH (n:Node) where id(n) = 1 return sum(n.prop)

but instead of 10, I'm only receiving the error statement:

SUM(n.prop) can only handle numerical values, or null.

what am I doing wrong and how should it be? many thanks.

Upvotes: 4

Views: 1003

Answers (2)

InverseFalcon
InverseFalcon

Reputation: 30397

The aggregation functions in Cypher are meant to operate across rows, not upon the contents of a list per row.

You could UNWIND the list back to rows and then get the sum() across the rows, or use the reduce() function approach as suggested by FrobberOfBits.

To supplement this, if using APOC Procedures one of the collection helper functions is apoc.coll.sum(), which takes in a list and outputs the summation of all elements in the list.

Upvotes: 0

FrobberOfBits
FrobberOfBits

Reputation: 18002

The reason you're getting this error is that you're passing sum a list and it's expecting a number. You can't sum a list. What would the sum of ["Hello", "Goodbye"] be? Sum is intended to be used to do things like sum integer properties.

You can use the reduce function to sum items in a list, like this:

create (f:Foo { myList: [1,2,3,4,5] });

match (f:Foo) with f return reduce(total=0, number in f.myList | total + number);
+------------------------------------------------------+
| reduce(total=0, number in f.myList | total + number) |
+------------------------------------------------------+
| 15                                                   |
+------------------------------------------------------+

Reduce is one of the list functions in cypher. What reduce really does is take a list and "reduce it down" to a single value. How does it know how to reduce? Via that last expression. We start with a total of zero, add whatever item is in the array, and keep doing that until the array is reduce to a single integer.

Upvotes: 2

Related Questions