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 。 |
说明:返回值的类型取决于提供的参数,以及表达式的语义。
示例
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 |
+---------------------+-----+--------+