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

问题描述 投票:0回答:1

我已经在名为“ mapfun”和“ reducefun”的“ system.js”集合中存储了两个函数,我正尝试从Java调用这些函数。我试图通过MapReduceCommand调用这些函数。我无法调用这些功能。谁能帮我这个忙。这两个函数看起来像这样// mapfun

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

// reducefun

{ "_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; }" } }

和我的mapreduce命令看起来像这样

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;};";

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

javascript java mongodb mapreduce
1个回答
0
投票

潜在的问题是为每个函数调用重新分配了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框架在调用map函数时将this分配给当前正在检查的文档。当从map函数内部调用存储的函数时,它会得到自己的this。但是,通过将函数称为testfun(this),会将映射函数的原始this上下文作为参数提供给存储的函数。

© www.soinside.com 2019 - 2024. All rights reserved.