Wednesday, June 20, 2012

Scope variable not workign in MongoDB MapReduce function

So I am trying to create map reduce aggregation functions. Since I need to aggregate on multiple dimensions, I don't want to copy/paste map and reduce function and only change the dimension from one to another.

I follow the manual http://www.mongodb.org/display/DOCS/MapReduce and defines the scope variable to pass in the dimension info:


// the map function
var map = function() {
    var dimension = this[dimension] ? this[dimension] : "_";
    var key = this.inst + "|" + this.bar + "|" + dimension;
    var result = {hit: 1};
    emit(key, result);
};
// the statement to call mapreduce
db.foo.mapReduce(map, reduce, {
  out: {inline: 1}, 
  query: q, 
  scope: {dimension: "red"}});

I run the above map reduce and found the dimension is always empty unless I noticed that dimension is redefined in the map function. Change the map funciton to the following solves the problem:
// the map function
var map = function() {
    var d= this[dimension] ? this[dimension] : "_"; // changed
    var key = this.inst + "|" + this.bar + "|" + d; // changed
    var result = {hit: 1};
    emit(key, result);
};

1 comment:

  1. scope variables are placed in global scope. ( dimension NOT this.dimension)
    this represents a single record ( or document ) and you access the attributes via this[attr]

    first example tries to overwrite scope variable from 'red' to this.dimension OR "_"
    second example ignores scope variable and uses this.dimension to create var d.

    ReplyDelete