RethinkDB: UNION ALL Example

Doing a “UNION ALL” in RethinkDB is fairly simple: you take a dataset, and add a “union” predicate to the end, with another dataset:

r.db('test')
 .table('users')
 .filter( 
    (x) => x('user_name').match('test ') 
  )
 .union(
   r.db('test')
    .table('users')
    .filter(
      (x) => x('user_name').match('9')
    )
 )

It’s worth noting that this is very different from SQL: rows are not de-duplicated. Syntactically, the two datasets live at the same level in SQL, whereas in this code example, the second dataset is nested.

If you want this to behave like a normal UNION, add a DISTINCT:

r.db('test')
 .table('users')
 .filter( (x) => x('user_name').match('test ') )
 .union(
   r.db('test')
    .table('users')
    .filter(
      (x) => x('user_name').match('9')
    )
 )
 .distinct()

Leave a Reply

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