mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

map_reduce swallows nested result values.

Open jaywhy13 opened this issue 13 years ago • 4 comments

Hi, I was trying to do a nested map reduce result. I can run this code against mongo directly... I basically am doing several group bys...

db.community_asset_history.insert({"asset_id" : 1, "community" : "UWI", "time_spent" : 10});
db.community_asset_history.insert({"asset_id" : 1, "community" : "UWI", "time_spent" : 2});
db.community_asset_history.insert({"asset_id" : 1, "community" : "UWI", "time_spent" : 30});
db.community_asset_history.insert({"asset_id" : 1, "community" : "Liguanea", "time_spent" : 5});
db.community_asset_history.insert({"asset_id" : 1, "community" : "Liguanea", "time_spent" : 20});
db.community_asset_history.insert({"asset_id" : 1, "community" : "Half Way Tree", "time_spent" : 3});

function bucketSort(xFieldNames, yFieldName, data){
    var result = {};
    if(xFieldNames.length == 1){
        // base case...
        var bucket = [];
        var xFieldName = xFieldNames[0];
        var values = {};
        for(var i in data){
            var record = data[i];
            var formattedRecord = {};
            var key = record[xFieldName];
            var value = record[yFieldName];
            if(!values[key]){
                values[key] = [];
            }
            values[key].push(value);
        }

        for(key in values){
            var valueArr = values[key];
            var value = Array.sum(valueArr);
            var formattedRecord = {};
            formattedRecord[xFieldName] = key;
            formattedRecord[yFieldName] = value;
            bucket.push(formattedRecord);
        }


        return {"value" : bucket};
    } else {
        var xFieldName = xFieldNames[0];
        var tmp = [];
        for(var i = 1; i < xFieldNames.length; i++){
            tmp.push(xFieldNames[i]);
        };
        xFieldNames = tmp;

        var xFieldValues = {};

        for(var i in data){
            var record = data[i];
            var xFieldValue = record[xFieldName];
            if(!xFieldValues[xFieldValue]){
                xFieldValues[xFieldValue] = [];
            }

            var formattedRecord = {};
            for(var x = 0; x < xFieldNames.length; x++){
                var _xFieldName = xFieldNames[x];
                formattedRecord[_xFieldName] = record[_xFieldName];
            }
            formattedRecord[yFieldName] = record[yFieldName];
            //console.log("Adding record: ", formattedRecord);
            xFieldValues[xFieldValue].push(formattedRecord);
        }

        // Recursively sort each bucket..
        for(var xFieldValue in xFieldValues){
            var bucket = xFieldValues[xFieldValue];
            result[xFieldValue] = bucketSort(xFieldNames, yFieldName, bucket).value;
        }
    }
    return result;
}

function mapFunction(){
    emit(this.asset_id, {"community" : this.community, "time_spent" : this.time_spent});
}

function reduceFunction(assetId, values){
    return bucketSort(["community"], "time_spent", values);
}

db.community_asset_history.mapReduce(mapFunction, reduceFunction, {out: "historyResults", scope:{"bucketSort" : bucketSort}});
db.historyResults.find().forEach(printjson);
db.historyResults.drop()

I get the following results:

{
        "_id" : 1,
        "value" : {
                "value" : [
                        {
                                "community" : "UNIVERSITY",
                                "time_spent" : null
                        },
                        {
                                "community" : "BEVERLY HILLS",
                                "time_spent" : "5"
                        },
                        {
                                "community" : "LIGUANEA",
                                "time_spent" : "15"
                        },
                        {
                                "community" : "UWI",
                                "time_spent" : 42
                        },
                        {
                                "community" : "Liguanea",
                                "time_spent" : 25
                        },
                        {
                                "community" : "Half Way Tree",
                                "time_spent" : 3
                        }
                ]
        }
}

When running through MongoEngine, I setup the map function and I put both functions into the reduce function so my reduce function can see the bucketSort function. I get this...

[{'name': 1.0, 'value': {}}]

Some how the "value" is getting chopped off.

jaywhy13 avatar Aug 08 '13 08:08 jaywhy13

In addition, when I try saving the code to a collection, the same thing is saved. Some how the value is truncated?

jaywhy13 avatar Aug 08 '13 08:08 jaywhy13

Not sure thats a MongoEngine issue?!

rozza avatar Aug 08 '13 08:08 rozza

Just a little lost here I guess, quite a noob. Thing is, I tried it first in Mongo DB just to be sure it would work. Then I tried to bring it into MongoEngine and the "value" was empty. Perhaps I'm not sure of the best way to do the "conversion". I figure there are many ways I could have gone wrong when I tried converting it for use with your map_reduce function (excellent framework btw!!!!).

  • Does MongoEngine handle dictionary returns from the reduce method? I'm not returning a single value or number, would that be a problem?
  • I don't emit a value, I'm emitting a dictionary. How else could I dig in to see what's happening?

jaywhy13 avatar Aug 08 '13 13:08 jaywhy13

Well you're right, doesn't seem to be a problem with MongoEngine at all. It was really just a problem of scope. The real question is how do you add a JS function into the scope for a map reduce. The docs need to be updated with examples for Map Reduce.

This does not work..

bucket_sort_function = """
 function bucketSort(){ ... }
"""
scope = dict(bucketSort=bucket_sort_function)
Location.objects.map_reduce(map_function, reduce_function, output="inline", scope=scope)

I fixed my problem by including the bucketSort code AFTER the reduceFunction in the same block... ie.

reduceFunction = """
function reduceF(key, values){ ... };
function bucketSort(){ ... };
"""

Doing it the other way around didn't work. I'm not sure how the block gets evaluated but it became obvious that the first function was just taken to be the reduce function.

jaywhy13 avatar Aug 08 '13 14:08 jaywhy13