3
votes

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?

1

1 Answers

3
votes

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}