3

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"
    }
  }
]
kuza
  • 2,761
  • 3
  • 22
  • 56
  • 1
    What if there are multiple documents from the same collection? Shouldn't `foo` and `bar` be arrays containing all documents from the respective collection? – CodeManX Feb 23 '18 at 09:48
  • In my question, there is (possibly not clear) constraint that collection of the documents are unique meaning there will be no more than one document per collection. I’ve made another QA just for you https://stackoverflow.com/a/48971985/7598113 – kuza Feb 25 '18 at 09:19

1 Answers1

3
  • 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}
)
kuza
  • 2,761
  • 3
  • 22
  • 56