6

I know there's the built-in _stats function that gives you sum, count, min, max, and sumsqr. What I'd like to know is how to calculate just the max in a map-reduce way. I can't come up with a reduce function that will work without some more information.

The only thing I can think of is to use sorting on the value and pick off the first value.

My map function looks like this:

function(doc){
  emit(null, doc.value);
}
PPC-Coder
  • 3,522
  • 2
  • 21
  • 30
  • 1
    Your workaround (sorting by value and picking the first or last entry) will not work with your map function - a view is sorted by key, so you would need to emit doc.value instead of null as a key. But instead of such workaround you can combine the map function you have with an appropriate reduce function. – titanoboa Apr 11 '12 at 16:37

2 Answers2

12

This may be also solved by the following

function (key, values, rereduce) {
  return Math.max.apply({}, values);
}
red_trumpet
  • 601
  • 1
  • 6
  • 15
8

The couchdb wiki provides a simple example for sum.

Instead of returning the sum of values, a reduce function for max should return the max of the values array. Since calculating the maximum is commutative, associative etc. you do not need to worry about rereduce.

function (key, values, rereduce) {
    // Return the maximum numeric value.
    var max = -Infinity
    for(var i = 0; i < values.length; i++)
        if(typeof values[i] == 'number')
            max = Math.max(values[i], max)
    return max
}
JasonSmith
  • 72,674
  • 22
  • 123
  • 149
titanoboa
  • 2,548
  • 15
  • 12