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

示例

  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. +------+------+-----+
  21. | 34 | 29 | 163 |
  22. +------+------+-----+
  23. | 34 | 33 | 167 |
  24. +------+------+-----+
  25. | 34 | 26 | 160 |
  26. +------+------+-----+
  27. | 34 | 34 | 168 |
  28. +------+------+-----+
  29. | 34 | 37 | 171 |
  30. +------+------+-----+
  31. nebula> LOOKUP ON player WHERE player.name == "Tony Parker" \
  32. | GO FROM $-.VertexID over follow \
  33. WHERE follow.degree != reduce(totalNum = 5, n IN range(1, 3) | $$.player.age + totalNum + n) \
  34. YIELD $$.player.name AS id, $$.player.age AS age, follow.degree AS degree;
  35. +---------------------+-----+--------+
  36. | id | age | degree |
  37. +---------------------+-----+--------+
  38. | "Tim Duncan" | 42 | 95 |
  39. +---------------------+-----+--------+
  40. | "LaMarcus Aldridge" | 33 | 90 |
  41. +---------------------+-----+--------+
  42. | "Manu Ginobili" | 41 | 95 |
  43. +---------------------+-----+--------+