MaiaVictor
MaiaVictor

Reputation: 52957

Why couchdb's reduce is implemented this way?

For example, this is a function that returns the sum and length of a row:

function(key, values, rereduce) {
  var result = {total: 0, count: 0};
  for(i=0; i < values.length; i++) {
    if(rereduce) {
        result.total = result.total + values[i].total;
        result.count = result.count + values[i].count;
    } else {
        result.total = sum(values);
        result.count = values.length;
    }
  }
  return(result);
}

It looks like you have to define:

Why is this so weird? A tradicional approach could be described as simple as:

reduce = {
    op: function(accumulated,val){
        return {total:accumulated.total + val, count:accumulated.count++};
    },
    initial: {total:0, count:0}
}

Which holds enough information to either reduce the entire array and update it for new values...!

Upvotes: 2

Views: 118

Answers (1)

djc
djc

Reputation: 11711

The reduce phase is repetitive because it makes storage/caching easier. You should imagine the result of reduce functions as a tree. To reduce a certain contiguous subset of nodes, you can largely use pre-calculated reduction values (and a few original ones), such that you don't have to descend the entire tree/re-calculate values for all of the nodes within the queried range.

I hope that clears it up a little, it's kind of hard to explain.

Upvotes: 2

Related Questions