Skip to content

reduce() function

OpenCypher Compatibility

In openCypher, the function reduce() is not defined. nGQL implements reduce() function as the Cypher way.

Syntax

reduce() returns the value resulting from the application of an expression on each successive element in a list in conjunction with the result of the computation thus far. This function will iterate through each element e in the given list, run the expression on e — taking into account the current partial result — and store the new partial result in the accumulator. This function is analogous to the fold or reduce method in functional languages such as Lisp and Scala.

reduce(accumulator = initial, variable IN list | expression)
  • Arguments:
Name Description
accumulator A variable that will hold the result and the partial results as the list is iterated.
initial An expression that runs once to give a starting value to the accumulator.
list An expression that returns a list.
variable The closure will have a variable introduced in its context. We decide here which variable to use.
expression This expression will run once per value in the list, and produce the result value.
  • Returns:

The type of the value returned depends on the arguments provided, along with the semantics of expression.

Example

nebula> RETURN reduce(totalNum = 10, n IN range(1, 3) | totalNum + n) AS r;
+----+
| r  |
+----+
| 16 |
+----+

nebula> RETURN reduce(totalNum = -4 * 5, n IN [1, 2] | totalNum + n * 2) AS r;
+-----+
| r   |
+-----+
| -14 |
+-----+
nebula> MATCH p = (n:player{name:"LeBron James"})<-[:follow]-(m) \
        RETURN      nodes(p)[0].age AS src1,  \
                    nodes(p)[1].age AS dst2,  \
                    reduce(totalAge = 100, n IN nodes(p) | totalAge + n.age) AS sum
+------+------+-----+
| src1 | dst2 | sum |
+------+------+-----+
| 34   | 31   | 165 |
+------+------+-----+
| 34   | 29   | 163 |
+------+------+-----+
| 34   | 33   | 167 |
+------+------+-----+
| 34   | 26   | 160 |
+------+------+-----+
| 34   | 34   | 168 |
+------+------+-----+
| 34   | 37   | 171 |
+------+------+-----+

nebula> LOOKUP ON player WHERE player.name == "Tony Parker" |  GO FROM $-.VertexID over follow WHERE follow.degree != reduce(totalNum = 5, n IN range(1, 3) | $$.player.age + totalNum + n) YIELD $$.player.name AS id, $$.player.age AS age, follow.degree AS degree
+---------------------+-----+--------+
| id                  | age | degree |
+---------------------+-----+--------+
| "Tim Duncan"        | 42  | 95     |
+---------------------+-----+--------+
| "LaMarcus Aldridge" | 33  | 90     |
+---------------------+-----+--------+
| "Manu Ginobili"     | 41  | 95     |
+---------------------+-----+--------+

Last update: March 17, 2021
Back to top