【问题标题】:MongoDB map reduce function syntaxMongoDB map reduce函数语法
【发布时间】:2012-08-11 23:48:42
【问题描述】:

我正在尝试将此 sql 查询转换为 map reduce

select
    o_orderpriority, 
    count(*) as order_count
from 
    orders
where 
    o_orderdate >= date '1993-07-01'
    and o_orderdate < date '1993-07-01' + interval '3' month
    and exists (
        select 
        *
        from 
        lineitem
        where 
        l_orderkey = o_orderkey
        and l_commitdate < l_receiptdate
    )
group by 
    o_orderpriority
order by 
    o_orderpriority;

我试过下面的 map reduce 功能

    db.runCommand({
    mapreduce: "orders",
    query: {
        o_orderdate: {'$gte': new Date("July 01, 1993")},
        o_orderdate: {'$lt': new Date("Oct 01, 1993")}
    },
    map: function Map() {
            for(var i in this.o_lineitem) {
                if( this.o_lineitem[i].l_commitdate < this.o_lineitem[i].l_receiptdate) {
                    var o_orderpriority = this.o_lineitem[i].o_orderpriority;
                    emit( o_orderpriority, {count: 1} );
                }
            }
        },
    reduce: function(key, values) {
                var count= 0;
                for (var i = 0; i < values.length; i++) {
                    count+= values[i];
                }
                return count;
            },
    out: 'query004'
});

当我跑步时,我会收到跟随警报

8 月 11 日星期六 20:44:32 SyntaxError: missing ) after condition (shell):9

对我来说,没有 ) 丢失,是吗?

我做了@Stenie 指出的更正,但现在我遇到了以下问题

{
        "assertion" : "value too large to reduce",
        "assertionCode" : 13070,
        "errmsg" : "db assertion failure",
        "ok" : 0
}

【问题讨论】:

  • 您缺少一个“。”在第 9 行: if( this.o_lineitem[i].l_commitdate
  • @AsyaKamsky 我指出了这一点,但问题仍然存在:Sun Aug 12 09:03:31 SyntaxError: missing ) after argument list (shell):10
  • @ulima69: 第 10 行有 emit(this.o_lineitem[i].o_orderpriority, count_order: 1); 但应该是 emit(this.o_lineitem[i].o_orderpriority, count_order);
  • @ulima69:哎呀,应该已经阅读了 reduce() .. 所以认为你真的想要:emit(this.o_lineitem[i].o_orderpriority, { count_order: 1 })。请注意,您的 reduce 正在使用 order_count 并且似乎没有将任何结果写入 ret 值。
  • 只需使用 emit(this.o_lineitem[i].o_orderpriority, 1) - 您不需要发出文档。

标签: mongodb mapreduce


【解决方案1】:

问题是你的 emit 和你的 reduce 函数没有返回相同的东西。

您的地图函数发出值:

{count: 1}

这意味着你的 reduce 必须返回相同的格式。

您在 reduce 中返回一个简单的值:

return count;

您可以将您的 emit 更改为仅发出 1 而不是 JSON 文档,然后您不必更改您的 reduce,否则更改您的 reduce 以返回 JSON 文档 {count: X},其中 X 是计算的计数。

仅供参考,导致错误“值太大而无法减少”的原因是,一旦您像这样混合您的类型,“+”运算符就会开始连接您的值而不是添加它们,最终它变得太大。要了解如何调试它,我推荐 Troubleshooting MapReduce 页面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多