Search code examples
rethinkdbarray-mergereql

Rethink merge array


I have a query -

 r.table('orgs')
        .filter(function(org) {
            return r.expr(['89a26384-8fe0-11e8-9eb6-529269fb1459', '89a26910-8fe0-11e8-9eb6-529269fb1459'])
            .contains(org('id'));
        })
        .pluck("users")

This returns following output-

{
"users": [
"3a415919-f50b-4e15-b3e6-719a2a6b26a7"
]
} {
"users": [
"d8c4aa0a-8df6-4d47-8b0e-814a793f69e2"
]
}

How do I get the result as -

[
 "3a415919-f50b-4e15-b3e6-719a2a6b26a7","d8c4aa0a-8df6-4d47-8b0e-814a793f69e2"
]

Solution

  • First, don't use that complicated and resource-consuming .filter directly on a table. Since your tested field is already indexed (id), you can:

    r.table('orgs').getAll('89...59', '89...59')
    

    or

    r.table('orgs').getAll(r.args(['89...59', '89...59']))
    

    which is way faster (way!). I recently found this article about how faster that is.

    Now to get an array of users without the wrapping, using the brackets operation:

    r.table('orgs').getAll(...).pluck('users')('users')
    

    will provide a result like

    [
      '123',
      '456'
    ],
    [
      '123',
      '789'
    ]
    

    We just removed the "users" wrapping, but the result is an array of arrays. Let's flatten this 2D array with .concatMap:

    r.table('orgs').getAll(...).pluck('users')('users').concatMap(function (usrs) {
      return usrs;
    })
    

    Now we've concatenated the sub-arrays into one, however we see duplicates (from my previous result example, you'd have '123' twice). Just .distinct the thing:

    r.table('orgs').getAll(...).pluck('users')('users').concatMap(function (usrs) {
      return usrs;
    }).distinct()
    

    From the example I took, you have now:

    '123',
    '456',
    '789'
    

    Et voilà!