Zach Smith
Zach Smith

Reputation: 8961

CouchDB: How to use array keys in Map functions when using Reduce?

I would like to write a MapReduce function in CouchDB where the Map function emitted keys as arrays, but the reduce function used only one of the values in the map key. for example:

The Map function:

function(doc) {
    if (doc.type_ === 'survey') {
        emit([doc.timeRecorded_, doc.imei_], 1);
    };
};

The Reduce function:

function(k,v) {

  // How to handle only the doc.imei_ as the value?
  // Or, alternatively, how to filter based on timeRecorded_ somewhere other than the map function?
  return sum(v)
}

timeRecorded_ in an EPOCH number, so there will be no duplications (except by chance). If I were to aggregate on it then it would need to be rounded to a 'day' value. Alternatively the data could be prepared in such a way that the timeRecorded_ was already rounded in the source data (maybe changed to dateRecorded_)

Upvotes: 1

Views: 351

Answers (1)

Aurélien Bénel
Aurélien Bénel

Reputation: 3842

A well-known pattern for this problem is to split the date into an array (e.g. [year, month, day, hour, minute]; intervals could be different but the order is to be kept) and use the array as the key in the map function.

Therefore you'll be able to reduce rows according to the group_level you need (e.g. "by year", "by month", "by day", "by hour", "by minute", etc.).

Source: http://blog.couchbase.com/understanding-grouplevel-view-queries-compound-keys

Upvotes: 2

Related Questions