问题描述
我知道有内置的_stats
函数,可为您提供求和,计数,最小,最大和sumsqr.我想知道的是如何以map-reduce的方式只计算最大值.如果没有更多的信息,我将无法提供一个减少功能.
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.
我的地图功能如下:
function(doc){
emit(null, doc.value);
}
推荐答案
couchdb Wiki提供了一个简单的总和的示例.
The couchdb wiki provides a simple example for sum.
max的reduce函数应该返回values数组的max,而不是返回值的总和.由于计算最大值是可交换的,可关联的等,因此您不必担心会减少.
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
}
这篇关于如何在CouchDB中使用Map-Reduce计算最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!