MapReduce

来源:互联网 发布:论大数据的机遇和挑战 编辑:程序博客网 时间:2024/06/08 12:04

转自http://chenzhou123520.iteye.com/blog/1629777

应用场景:

使用MapReduce找出一个集合中所有的键的个数,mongo shell代码如下:

定义map function:

  1. map = function () {  
  2.     for (var key in this) {  
  3.         emit(key, {count:1});  
  4.     }  
  5. }  

定义reduce function:

  1. reduce = function (key, emits) {  
  2.     total = 0;  
  3.     for (var i in emits) {  
  4.         total += emits[i].count;  
  5.     }  
  6.     return {count:total};  
  7. }  

执行MapReduce操作:

  1. mr = db.runCommand({"mapreduce":"users","map":map,"reduce":reduce})  

以上都是书上的代码,但是执行后没有正常返回,而是返回了如下结果:

  1. {  
  2.     "assertion" : "'out' has to be a string or an object",  
  3.     "assertionCode" : 13606,  
  4.     "errmsg" : "db assertion failure",  
  5.     "ok" : 0  
  6. }  

网上百度了下才知道原来1.8以上的版本需要指定out的输出

修改了执行MapReduce命令后执行正常,命令如下:

  1. mr = db.runCommand({"mapreduce":"users","map":map,"reduce":reduce,"out":{inline:1}})  

也可以使用如下命令方式:

  1. db.users.mapReduce(map,reduce,{out:{inline:1}})  

执行后返回结果如下:

  1. {  
  2.     "results" : [  
  3.         {  
  4.             "_id" : "_id",  
  5.             "value" : {  
  6.                 "count" : 3  
  7.             }  
  8.         },  
  9.         {  
  10.             "_id" : "age",  
  11.             "value" : {  
  12.                 "count" : 1  
  13.             }  
  14.         },  
  15.         {  
  16.             "_id" : "email",  
  17.             "value" : {  
  18.                 "count" : 1  
  19.             }  
  20.         },  
  21.         {  
  22.             "_id" : "emails",  
  23.             "value" : {  
  24.                 "count" : 1  
  25.             }  
  26.         },  
  27.         {  
  28.             "_id" : "favorite book",  
  29.             "value" : {  
  30.                 "count" : 1  
  31.             }  
  32.         },  
  33.         {  
  34.             "_id" : "hobby",  
  35.             "value" : {  
  36.                 "count" : 1  
  37.             }  
  38.         },  
  39.         {  
  40.             "_id" : "name",  
  41.             "value" : {  
  42.                 "count" : 3  
  43.             }  
  44.         },  
  45.         {  
  46.             "_id" : "score",  
  47.             "value" : {  
  48.                 "count" : 2  
  49.             }  
  50.         }  
  51.     ],  
  52.     "timeMillis" : 311,  
  53.     "counts" : {  
  54.         "input" : 3,  
  55.         "emit" : 13,  
  56.         "reduce" : 3,  
  57.         "output" : 8  
  58.     },  
  59.     "ok" : 1  
  60. }  

 

官网文档地址:http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Outputoptions  

 


0 0
原创粉丝点击