如何在 CouchDB 中使用 Map-Reduce 计算最大值? [英] How to calculate Max value using Map-Reduce in CouchDB?

查看:24
本文介绍了如何在 CouchDB 中使用 Map-Reduce 计算最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有内置的 _stats 函数可以为您提供 sum、count、min、max 和 sumsqr.我想知道的是如何以 map-reduce 方式计算最大值.如果没有更多信息,我无法想出一个可以工作的 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.

我的地图功能如下所示:

My map function looks like this:

function(doc){
  emit(null, doc.value);
}

推荐答案

couchdb wiki 提供了一个简单的 总和的示例.

The couchdb wiki provides a simple example for sum.

max 的 reduce 函数应该返回 values 数组的最大值,而不是返回值的总和.由于计算最大值是可交换的、关联的等,因此您无需担心 rereduce.

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 计算最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆