Search code examples
graph-databasesarangodbaql

How do I combine the output of two return variables into one in ArangoDB?


Beginner with ArangoDB here:

I have two outputs stored in two variables, say: a and b.
The structure of the items in variable a and b are exactly the same, but with different data. Example as follows:

a = {
    "user": "Thor Odinson",
    "city": "New York",
    "action": "Lives"
}

b = {
    "user": "Thor Odinson",
    "city": "New York",
    "action": "Childhood"
}

How would I combine the output from the two variables into one as follows?

{
    "user": "Thor Odinson",
    "city": "New York",
    "action": ["Lives", "Childhood"]
}

Ideally, combine the two documents with user and city as common denominator, and action merged into an array? Not sure if Arango has a function like that natively, but any help towards the right direction would be a great help too!
I am open to writing the logic in my code instead, but I'd like to avoid that as much as possible.

I've been playing around with COLLECT, UNION, and MERGE but with no luck.


Solution

  • Defining data as

    LET a = {
        "user": "Thor Odinson",
        "city": "New York",
        "action": "Lives"
    }
    
    LET b = {
        "user": "Thor Odinson",
        "city": "New York",
        "action": "Childhood"
    }
    
    LET data = [a,b]
    

    To get the desired result for data, this should get you started:

    FOR i IN data
        COLLECT user = i.user, city = i.city INTO groups = i.action 
        RETURN {"user": user, "city": city, "action": groups}
    

    That gives the desired result:

    [
      {
        "user": "Thor Odinson",
        "city": "New York",
        "action": [
          "Lives",
          "Childhood"
        ]
      }
    ]
    

    If you need more control over the variables returned, use KEEP:

    FOR i IN data
        LET action = i.action
        COLLECT user = i.user, city = i.city INTO groups KEEP action
        RETURN {"user": user, "city": city, "action": groups[*].action}