1

我正在运行 map reduce 操作并以错误的数据结束。这是我的 map 和 reduce 函数:

var map_analytics = function() {
    var key = this.owner;
    if (this.apikey == null) {
        var value = {api_call_with_key: 0, api_call_without_key: 1};
    } else {
        var value = {api_call_with_key: 1, api_call_without_key: 0};
    }
    emit(key, value);
};

var reduce_analytics  = function(key_owner, api_calls) {
    today = new Date();
    firstofmonth = new Date(today.getFullYear(), today.getMonth(), 1);
    reduced_val = {period: firstofmonth, analytics: {api_call_with_key: 0, api_call_without_key: 0}};
    api_calls.forEach(function(value) {
        reduced_val.analytics.api_call_with_key += value.api_call_with_key;
        reduced_val.analytics.api_call_without_key += value.api_call_without_key;
    });
    return reduced_val;
};

现在当我运行我的地图减少时:

db.statistics.mapReduce(map_analytics, reduce_analytics, {out: { reduce: "analytics" }, query: { request_date: { $gte: firstofmonth}}})

我明白了:

{
        "_id" : ObjectId("5136d880136b961c98c9a62f"),
        "value" : {
                "period" : ISODate("2013-05-01T06:00:00Z"),
                "analytics" : {
                        "api_call_with_key" : NaN,
                        "api_call_without_key" : NaN
                }
        }
}

知道为什么我得到 NaN 而不是实际值吗?

一个更简单的版本可以工作:

var reduce_analytics  = function(key_owner, api_calls) {
    reduced_val = {api_call_with_key: 0, api_call_without_key: 0};
    api_calls.forEach(function(value) {
        reduced_val.api_call_with_key += value.api_call_with_key;
        reduced_val.api_call_without_key += value.api_call_without_key;
    });
    return reduced_val;
};

并生产

{
        "_id" : ObjectId("5143b2c8136b9616343dacec"),
        "value" : {
                "api_call_with_key" : 0,
                "api_call_without_key" : 2,
                "total_api_calls" : 2
        }
}

如何输出更复杂的对象?

4

2 回答 2

1

您不能在 map 和 reduce 之间更改值的格式。

换句话说,当您的地图发出 (key, VALUE) 时,您的 reduce 函数必须返回相同格式的 VALUE。

因此,如果您想将日期作为您价值的一部分,您需要在映射阶段将其放入。如果您按键分组,则日期应该是关键文档的一部分。

此外,如果可以的话,我建议使用聚合框架——它比 map-reduce 快得多。

于 2013-05-08T04:41:15.697 回答
0

尝试这个:

api_calls.forEach(function(value) {
    reduced_val.analytics.api_call_with_key += Number(value.api_call_with_key);
    reduced_val.analytics.api_call_without_key += Number(value.api_call_without_key);
});
于 2013-05-08T04:41:34.633 回答