Combining Graph Traversals

Finding the start vertex via a geo query

Our first example will locate the start vertex for a graph traversal via a geo index. We use the city graph and its geo indices:

Cities Example Graph

arangosh> var examples = require("@arangodb/graph-examples/example-graph.js");
arangosh> var g = examples.loadGraph("routeplanner");

We search all german cities in a range of 400 km around the ex-capital Bonn: Hamburg and Cologne. We won't find Paris since its in the frenchCity collection.

Query:
  FOR startCity IN germanCity
    FILTER GEO_DISTANCE(@bonn, startCity.geometry) < @radius
      RETURN startCity._key
Bind Values:
{
  "bonn": [
    7.0998,
    50.734
  ],
  "radius": 400000
}
Query results:
[
  "Cologne",
  "Hamburg"
]

Lets revalidate that the geo indices are actually used:

Explain Query:
  FOR startCity IN germanCity
    FILTER GEO_DISTANCE(@bonn, startCity.geometry) < @radius
      RETURN startCity._key
Bind Values:
{
  "bonn": [
    7.0998,
    50.734
  ],
  "radius": 400000
}
Show explain output

And now combine this with a graph traversal:

Query:
  FOR startCity IN germanCity
    FILTER GEO_DISTANCE(@bonn, startCity.geometry) < @radius
      FOR v, e, p IN 1..1 OUTBOUND startCity
        GRAPH 'routeplanner'
      RETURN {startcity: startCity._key, traversedCity: v._key}
Bind Values:
{
  "bonn": [
    7.0998,
    50.734
  ],
  "radius": 400000
}
Show query result

The geo index query returns us startCity (Cologne and Hamburg) which we then use as starting point for our graph traversal. For simplicity we only return their direct neighbours. We format the return result so we can see from which startCity the traversal came.

Alternatively we could use a LET statement with a subquery to group the traversals by their startCity efficiently:

Query:
  FOR startCity IN germanCity
    FILTER GEO_DISTANCE(@bonn, startCity.geometry) < @radius
      LET oneCity = (
        FOR v, e, p IN 1..1 OUTBOUND startCity
          GRAPH 'routeplanner' RETURN v._key
      )
        RETURN {startCity: startCity._key, connectedCities: oneCity}
Bind Values:
{
  "bonn": [
    7.0998,
    50.734
  ],
  "radius": 400000
}
Show query result

Finally, we clean up again:

arangosh> examples.dropGraph("routeplanner");