Thursday, March 13, 2014

Mongo 2.4.9 - MapReduce

1. Map

function map_closest() {
    var pitt = [-80.064879, 40.612044];
    var phil = [-74.978052, 40.089738];

    function distance(a, b) {
        var dx = a[0] - b[0];
        var dy = a[1] - b[1];
        return Math.sqrt(dx * dx + dy * dy);
    }

    if (distance(this.loc, pitt) < distance(this.loc, phil)) {
        emit("pitt", 1);
    } else {
        emit("phil", 1);
    }
}

2. Reduce

2.1. Array.sum()

function reduce_closest(city, counts) {  
  return Array.sum(counts); 
}

2.2. for()

function reduce_closest(city, counts) {
 var total = 0;
 var length = counts.length;

 for (var i = 0; i < length; i++) {
  total += counts[i];
 }

 return total;
}

2.3. forEach()

function reduce_closest(city, counts) {
 var total = 0;

 counts.forEach(function(count) {
  total += count;
 });

 return total;
}

3. mapReduce

db.zips.mapReduce(
  map_closest, 
  reduce_closest, 
  { 
    query: { state: 'PA' }, 
    out: { inline: 1 } 
  }
)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.