MapReduce的用法

来源:互联网 发布:机房设计软件 编辑:程序博客网 时间:2024/06/02 01:58

MapReduce是聚合工具中的明星,count,distinct,group能做的事情,MapReduce都可以完成,它是一个可以轻松并行化到多个服务器的聚合方法.简单的说就是将大批量的工作(数据)分解(MAP)执行,然后再将结果合并成最终结果(REDUCE)。这样做的好处是可以在任务被分解后,可以通过大量机器进行并行计算,减少整个操作的时间。

 

1persons集合里面有如下数据,用MapReduce计算出每个国家的人数

map=function(){

          emit( this.country,{count: 1} ) ;

 }

 

 

reduce = function( key , values ){...

    var total = {count: 0}

      for ( var i=0; i<values.length; i++ )

         total.count += values[i].count; 

     return { count : total };

 

};

 

 

 

查询结果:

 

用java操作MapReduce

public static void main(String[]args){

  MongoDb db=new MongoDb("foobar");

  String map = "function() { emit(this.country, {count:1});}";
  String reduce = "function Reduce(key, values) {var total = {count:0}; for ( var i=0; i<values.length; i++ ) total.count += values[i].count;  ;return total;}";
  MapReduceOutput mop = db.mapReduce("persons", map, reduce, null,
    MapReduceCommand.OutputType.INLINE, null);
  Iterable<DBObject> itr = mop.results();
  long lCount = 0;
  for (DBObject dbObject : itr) {
   String _id = dbObject.get("_id").toString();
   Double dble = (Double) ((DBObject) dbObject.get("value"))
     .get("count");
   lCount = dble.longValue();
   System.out.println(_id + "  " + lCount);
  }

}

public   MapReduceOutput mapReduce(String collName,String map, String reduce,
  String outputTarget, OutputType outputType, DBObject queryObj) {
  DBCollection collection=db.getCollection(collName);
 return collection.mapReduce(map,reduce, null, MapReduceCommand.OutputType.INLINE, queryObj);
}

 

查询结果如下:

American  2
China  5
Korea  1

0 0
原创粉丝点击