Returning a single document of vertices and edges from AQL traversal

When I traverse in Arango, I get an array of json structures that look like this:

{
  "vertex" : {
    "_id" : "vertices/857831247835",
    "_key" : "857831247835",
    "_rev" : "857831247835",
  },
  "path" : {
    "edges" : [
      {
      "_id" : "edges/857831575515",
      "_key" : "857831575515",
      "_rev" : "857831575515",
      "_from" : "vertices/857831247835",
      "_to" : "vertices/857821417435",
    }
    ],
    "vertices" : [
      {
      "_id" : "vertices/857821417435",
      "_key" : "857821417435",
      "_rev" : "857821417435",
    },
    {
      "_id" : "vertices/857831247835",
      "_key" : "857831247835",
      "_rev" : "857831247835",
    }
    ]
  },
  "startVertex" : "vertices/857821417435"
}

      

Is there a way to get all edges / vertices found in the traversal into one structure like the one above using AQL?

+3


source to share


2 answers


In fact, you can use two ways to get the result:

A simple way to extend your AQL query:

FOR x IN (<<Your previous query here>>) RETURN {edges: x.path.edges, vertices: x.path.vertices, vertex: x.vertex, startVertex: x.startVertex}

More efficient way (you short-circuit the object creation): Register a custom function following: https://docs.arangodb.com/AqlExtending/Functions.html Use once arangosh

.

It should be something like this:



require("org/arangodb/aql/functions").register("myVisitors::flatVisitor", function (config, result, vertex, path) { result.push({ vertex: vertex, edges: path.edges, vertices: path.vertices}); });

And then in your AQL add an extra option visitor: "myVisitors::flatVisitor"

just like paths: true

.

BTW: paths: true

Will be ignored in this case as it was only used for our default visitor.

ADVICE. If you only want specific attributes in your result and not the complete document, return them only to the visitor. This will give a significant performance improvement.

+1


source


A bit old, but for the sake of new visitors to this question. another way is to accumulate edges from the path unambiguously (the syntax has the official arangojs client):



graph.traversal('verticies/startkey', {
    direction: 'any',
    init: `result.verticies = [];
    result.edges = [];`,
    visitor: `
        path.edges
            .forEach(function (x) {
                if (result.edges.indexOf(x) === -1) {
                    result.edges.push(x);
                }
            });
        result.verticies.push(vertex);
    `,
    uniqueness: {
        "vertices": "global",
        "edges": "global"
    }
});

      

0


source







All Articles