reduce函数

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

openCypher兼容性

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

语法

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

Note

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

示例

  1. nebula> RETURN reduce(totalNum = 10, n IN range(1, 3) | totalNum + n) AS r;
  2. +----+
  3. | r |
  4. +----+
  5. | 16 |
  6. +----+
  7. nebula> RETURN reduce(totalNum = -4 * 5, n IN [1, 2] | totalNum + n * 2) AS r;
  8. +-----+
  9. | r |
  10. +-----+
  11. | -14 |
  12. +-----+
  13. nebula> MATCH p = (n:player{name:"LeBron James"})<-[:follow]-(m) \
  14. RETURN nodes(p)[0].age AS src1, nodes(p)[1].age AS dst2, \
  15. reduce(totalAge = 100, n IN nodes(p) | totalAge + n.age) AS sum;
  16. +------+------+-----+
  17. | src1 | dst2 | sum |
  18. +------+------+-----+
  19. | 34 | 31 | 165 |
  20. | 34 | 29 | 163 |
  21. | 34 | 33 | 167 |
  22. | 34 | 26 | 160 |
  23. | 34 | 34 | 168 |
  24. | 34 | 37 | 171 |
  25. +------+------+-----+
  26. nebula> LOOKUP ON player WHERE player.name == "Tony Parker" \
  27. | GO FROM $-.VertexID over follow \
  28. WHERE properties(edge).degree != reduce(totalNum = 5, n IN range(1, 3) | properties($$).age + totalNum + n) \
  29. YIELD properties($$).name AS id, properties($$).age AS age, properties(edge).degree AS degree;
  30. +---------------------+-----+--------+
  31. | id | age | degree |
  32. +---------------------+-----+--------+
  33. | "Tim Duncan" | 42 | 95 |
  34. | "LaMarcus Aldridge" | 33 | 90 |
  35. | "Manu Ginobili" | 41 | 95 |
  36. +---------------------+-----+--------+

最后更新: October 27, 2021