kuza
kuza

Reputation: 3041

How to merge all results of AQL into single document with custom properties

I have an AQL query traversing graph that always should return a fixed amount of documents from a unique set of collections. So each collection will occur only once and with one document only.

I wish to merge them all into a single document under properties that reflects document’s collection name.

Query as simple as:

FOR v IN ANY "vertex/key" edge_collection RETURN v

Returns a sample result as:

[
  {
    "_key": "123",
    "_id": "foo/123",
    "_rev": "_WYhh0ji---",
    "foo_attribute": "lorem impsum"
  },
  {
    "_key": "456",
    "_id": "bar/456",
    "_rev": "_WYhh2ny---",
    "bar_attribute": "dolor sit amet"
  }
]

That I wish to get like this:

[
  {
    "foo": {
      "_key": "123",
      "_id": "foo/123",
      "_rev": "_WYhh0ji---",
      "foo_attribute": "lorem impsum"
    },
    "bar": {
      "_key": "456",
      "_id": "calendar/bar",
      "_rev": "_WYhh2ny---",
      "bar_attribute": "dolor sit amet"
    }
  }
]

Upvotes: 3

Views: 1305

Answers (1)

kuza
kuza

Reputation: 3041

  • In order to get collection name from document use PARSE_IDENTIFIER function that gives document’s collection name and key separately
  • Use square brackets comprehension to generate document property dynamically
  • Simply merge result of the query

Example:

RETURN MERGE(
    FOR v IN ANY "vertex/key" edge_collection
    RETURN {[PARSE_IDENTIFIER(v).collection]: v}
)

Upvotes: 3

Related Questions