简体   繁体   中英

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

and so on...

Lets say you need to find out how much money each user is owed, using a graph traversal. How do you implement this?

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)

This uses a sub-query, which means all values are returned, and then the SUM operation is executed on them.

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM