Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 901
Benoit D. Avatar asked Oct 25 '25 00:10

Benoit D.


1 Answers

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.

like image 115
FrobberOfBits Avatar answered Oct 27 '25 15:10

FrobberOfBits