ArangoDB - 如何在图遍历中执行计算? [英] ArangoDB - how to perform computations in graph traversals?
问题描述
我有一个简单的图表来跟踪我借钱给的人.所以图形看起来像这样:
I have a simple graph for keeping a track of people whom I have lent money to. So the graph looks like this:
userB -- owes to (amount: 200) --> userA
userC -- owes to (amount: 150) --> userA
等等...
假设您需要使用图遍历找出每个用户欠了多少钱.你如何实现这一点?
Lets say you need to find out how much money each user is owed, using a graph traversal. How do you implement this?
推荐答案
让我用 城市示例图顶点(城市)有一个数字属性,population
;边(公路)有一个数值属性distance
.
Let me explain this using the city example graph
Vertices (cities) have a numeric attribute, population
; Edges (highways) have a numeric attribute distance
.
检查我们期望总结的内容:
Inspecting what we expect to sumarize:
FOR v, e IN 1..1 INBOUND "frenchCity/Lyon" GRAPH "routeplanner"
RETURN {city: v, highway: e}
总结所有穿越城市的人口很容易:
Summing up the population of all traversed cities is easy:
RETURN SUM(FOR v IN 1..1 INBOUND "frenchCity/Lyon" GRAPH "routeplanner"
RETURN v.population)
这里使用子查询,即返回所有值,然后对它们执行SUM
操作.
This uses a sub-query, which means all values are returned, and then the SUM
operation is executed on them.
最好使用 COLLECT AGGREGATE
总结遍历过程中的属性.
Its better to use COLLECT AGGREGATE
to sum up the attributes during the traversal.
因此,虽然在城市人口及其距离的背景下,对这些数字求和可能没有意义,但无论如何我们还是要这样做:
So while in the context of population of cities and their distances it may not make sense to sumerize these numbers, lets do it anyways:
FOR v, e IN 1..1 INBOUND "frenchCity/Lyon" GRAPH "routeplanner"
COLLECT AGGREGATE populationSum = SUM(v.population), distanceSum = SUM(e.distance)
RETURN {population : populationSum, distances: distanceSum}
这篇关于ArangoDB - 如何在图遍历中执行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!