Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under MongoDB java driver Mapreduce command scope; add functions to Scope

Is their a way to Execute a MongoDB map reduce job through the java driver in which you create a scope DBObject that contains functions.

I can execute my map reduce configuration in javascript where the passed in scope contains utility functions, but I can't figure out how to do this with the java driver.

I setup the scope using mapReduceCommand's

c.addExtraOption("scope",new BasicDBObject().append('average',function(){ return false;}));

However I can't get the mappers/reducers to recognize the scope component 'e.g.' average as a function. If I use quotes, the map reduce context thinks its a String, but if not, I can't seem to make the scope component parse.

How does one get a function in the scope component through the java driver?

Thanks to Ren's answer, Here is a spring bean configuration to set up a scope for the mongodb java driver with a function.

    <util:map id="mrScope" 
              key-type="java.lang.String" 
              value-type="java.lang.Object">
    <entry key="buckets"><bean class="com.mongodb.util.JSON" factory-method="parse"><constructor-arg value="[0,10,15,20,25,30,35,40,45,50,55,60,65]"/></bean></entry>
    <entry key="average">
        <bean class="org.bson.types.CodeWScope">
            <constructor-arg value="function () {var s = 0;for (var i = 0; i &gt; arguments.length; i++) s += arguments[i];return s / arguments.length;}"/>
            <constructor-arg><bean class="org.bson.BasicBSONObject"/></constructor-arg>
        </bean>
    </entry>
like image 705
gbegley Avatar asked Apr 05 '12 23:04

gbegley


2 Answers

The server code automatically converts the map and reduce into Javascript function, but not so with scope. To pass a function in the scope option, you can do this instead:

c.addExtraOption("scope", new BasicBSONObject("average",
  new CodeWScope("function(){ return false;}", new BasicBSONObject())));
like image 94
Ren Avatar answered Oct 17 '22 11:10

Ren


With the new api (3.0).. I found the below option is working

collection .mapReduce(map, reduce) .scope(new Document("key", value)) .limit(100);

like image 23
gsuresh92 Avatar answered Oct 17 '22 11:10

gsuresh92