Search code examples
arangodbaql

ArangoDB group results into one single key


I have a graph (which is a tree) composed by one vertex collection and one edge collection. I'm trying to make an AQL query to return some of them (max depth 2) in form of an object.

I'm using this query:

FOR v,e IN 0..1 OUTBOUND 'nodes/root' GRAPH 'myGraph' 
        OPTIONS { uniqueVertices: 'path', order: 'bfs' } 
RETURN {"nodes":v, "edges":e}

But I get this:

[
  {
    "nodes": {
      "_key": "root",
      "_id": "nodes/root",
      "metadata": {}
    },
    "edges": null
  },
  {
    "nodes": {
      "_key": "sys-1",
      "_id": "nodes/sys-1",
      "metadata": {}
    },
    "edges": {
      "_key": "sys-1-root",
      "_id": "relationships/sys-1-root",
      "_from": "nodes/root",
      "_to": "nodes/sys-1",
      "metadata": null
    }
  },
  {
    "nodes": {
      "_key": "sys-4",
      "_id": "nodes/sys-4",
      "metadata": {}
    },
    "edges": {
      "_key": "sys-4-root",
      "_id": "relationships/sys-4-root",
      "_from": "nodes/root",
      "_to": "nodes/sys-4",
      "metadata": null
    }
  }
]

And I want something like this:

[
   {
      "nodes":[
         {
            "_key":"root",
            "_id":"nodes/root",
            "metadata":{
               
            }
         },
         {
            "_key":"sys-1",
            "_id":"nodes/sys-1",
            "metadata":{
               
            }
         },
         {
            "_key":"sys-4",
            "_id":"nodes/sys-4",
            "metadata":{
               
            }
         }
      ],
      "edges":[
         null,
         {
            "_key":"sys-1-root",
            "_id":"relationships/sys-1-root",
            "_from":"nodes/root",
            "_to":"nodes/sys-1",
            "metadata":null
         },
         {
            "_key":"sys-4-root",
            "_id":"relationships/sys-4-root",
            "_from":"nodes/root",
            "_to":"nodes/sys-4",
            "metadata":null
         }
      ]
   }
]

I've been reading the documentation and other questions in stackoverflow but couldn't find a way to get this. Thanks!


Solution

  • This looks like a case tailor made for array contraction:

    LET res = (
      FOR v,e IN 0..1 OUTBOUND 'nodes/root' GRAPH 'myGraph' 
              OPTIONS { uniqueVertices: 'path', order: 'bfs' } 
      RETURN {"nodes":v, "edges":e}
    )
    RETURN {'nodes': res[*].nodes, 'edges': res[*].edges}