Search code examples
rethinkdbreql

Emit multiple values in RethinkDB map step


I have datasets that consist of arrays and single values

{
     "a": "18",
     "b": ["x","y","z"]
}

or arrays and arrays

{
     "a": ["g", "h", "i"],
     "b": ["x", "y", "z"]
}

and i plan to map out each combination (like "18-x", "18-y", "18-z" or "g-x", "g-y"...) to count these afterwards (or do anything else). I'm used to CouchDB with their emit function: I simply emitted multiple combinations per document. How is this supposed to be done in RethinkDB?

Note: The datasets are produced by a join


Solution

  • I would recommend making both fields always be arrays, even if the arrays sometimes only have a single value.

    If you do that, you can do this with concat_map:

    row('a').concatMap(function(a){
      return row('b').map(function(b){
        return a.add('-').add(b);
      });
    });
    

    If you want to continue using a mix of single values and arrays, you can do that by replacing r.row('a') with r.branch(r.row('a').typeOf().eq('ARRAY'), r.row('a'), [r.row('a')]).