跳转至

reduce 函数

reduce()将表达式逐个应用于列表中的元素,然后和累加器中的当前结果累加,最后返回完整结果。该函数将遍历给定列表中的每个元素e,在e上运行表达式并和累加器的当前结果累加,将新的结果存储在累加器中。这个函数类似于函数式语言(如 Lisp 和 Scala)中的 fold 或 reduce 方法。

openCypher 兼容性

在 openCypher 中,reduce()函数没有定义。nGQL 使用了 Cypher 方式实现reduce()函数。

语法

reduce(<accumulator> = <initial>, <variable> IN <list> | <expression>)
参数 说明
accumulator 在遍历列表时保存累加结果。
initial accumulator提供初始值的表达式或值。
variable 为列表引入一个变量,决定使用列表中的哪个元素。
list 列表或列表表达式。
expression 该表达式将对列表中的每个元素运行一次,并将结果累加至accumulator

Note

返回值的类型取决于提供的参数,以及表达式的语义。

示例

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" YIELD id(vertex) AS VertexID \
        |  GO FROM $-.VertexID over follow \
        WHERE properties(edge).degree != reduce(totalNum = 5, n IN range(1, 3) | properties($$).age + totalNum + n) \
        YIELD properties($$).name AS id, properties($$).age AS age, properties(edge).degree AS degree;
+---------------------+-----+--------+
| id                  | age | degree |
+---------------------+-----+--------+
| "Tim Duncan"        | 42  | 95     |
| "LaMarcus Aldridge" | 33  | 90     |
| "Manu Ginobili"     | 41  | 95     |
+---------------------+-----+--------+

最后更新: March 7, 2023