How to merge two arrays in RethinkDB

In RethinkDB, you can concatenate two arrays with the “add” function. It seems that this can detect the type of it’s arguments and behave accordingly, since this is also used for numerical addition.

In my case, I started with a table where each row contained an array:

{
  id: 1,
  entities: [
    {...}, {...}, {...}
  ]
},
{
  id: 2,
  entities: [
    {...}, {...}
  ]
}

By design of this application the values in “entities” were supposed to be the actual rows in the table, not nested in random groups, so I’ve written a query to flatten them into one giant array:

r.db('Watson')
 .table('description_s_TextGetRankedNamedEntities')
 .map( 
   function(row) {
     return row('entities');
   }
  )
  .reduce(
    function(left, right) {
      return r.add(left, right)
    })

The key here is you probably always need a “map” before a “reduce” so that your reduction step doesn’t get mixed arguments If you try to combine switching the shape of the entry data with the reduction, the “reduce” function would have to detect both left/right shapes to do the combination correctly, since it is designed to operate in parallel.

One Reply to “How to merge two arrays in RethinkDB”

Leave a Reply

Your email address will not be published. Required fields are marked *