繁体   English   中英

如何在java中的mapReduce中调用mongodb服务器端函数

[英]how to call mongodb server side function inside mapReduce in java

我在名为“mapfun”和“reducefun”的“system.js”集合中存储了两个函数,我试图从java调用这些函数。 我正在尝试通过 MapReduceCommand 调用这些函数。 我无法调用这些函数。 任何人都可以帮我解决这个问题。 这两个函数看起来像这样 //mapfun

{ "_id" : "mapfun","value" : { "code" : "function(){var criteria; if(this.speed > 70 ){ criteria="overspeed";emit(criteria,this.speed); } }" } }

//减少乐趣

{ "_id" : "reducefun", "value" : { "code" : "function(key,speed){ var total=0; for(var i=0;i<speed.length;i++){ total=total+speed[i]; } return total/speed.length; }" } }

我的 mapreducecommand 看起来像这样

MapReduceCommand command=new MapReduceCommand(collection, map, reduce, null, MapReduceCommand.OutputType.INLINE, null);
MapReduceOutput output=collection.mapReduce(command);

我已经将 map 和 reduce 函数作为字符串传递,其中我分别调用了 mapfun 和 reducefun,它看起来像这样

String map = "function (){var x=mapfun();"
                + "return x;};";
String reduce = "function(key, speed) {var y=reducefun(key,speed);"
                + "return y;};";

我在这里做错了什么以及如何纠正这个问题请帮助我解决这个问题。

潜在的问题是为每个函数调用重新分配了this变量。

为了演示,我从 mongo shell 运行了一个简短的测试。

拳头创建一个包含 1 个文档的集合:

MongoDB Enterprise replset:PRIMARY> db.maptest.find({},{_id:0})
{ "canary" : "tweet" }

然后创建一个存储函数,该函数将接受一个参数发出 2 个值,一个使用this ,一个使用传递的参数:

MongoDB Enterprise replset:PRIMARY> db.system.js.find()
{ "_id" : "testfun", "value" : { "code" : "function(arg){emit(\"this.canary\",this.canary),emit(\"arg.canary\",arg.canary)}" } }

然后在 mapReduce 调用中使用存储的函数:

MongoDB Enterprise replset:PRIMARY> db.maptest.mapReduce(function(){testfun(this)},function(a,b){return {a:a,b:b}},{out:{inline:1}})
{
    "results" : [
        {
            "_id" : "arg.canary",
            "value" : "tweet"
        },
        {
            "_id" : "this.canary",
            "value" : undefined
        }
    ],
...

如您所见, this.canary未定义,但arg.canary包含来自输​​入文档的值。

MapReduce框架受让人this调用地图功能时,目前正在审查的文件。 当从 map 函数内部调用存储的函数时,它会获得自己的this 但是,通过将函数作为testfun(this)调用,映射函数的原始this上下文作为参数提供给存储的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM