好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MongoDB学习笔记之MapReduce使用示例

一、mapreduce是根据map函数里调用的emit函数的第一个参数来进行分组的

Map-Reduce是一种计算模型,简单的说就是将大批量的工作(数据)分解(MAP)执行,然后再将结果合并成最终结果(REDUCE)。

使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数, Map 函数调用 emit(key, value), 遍历 collection 中所有的记录, 将key 与 value 传递给 Reduce 函数进行处理。Map 函数必须调用 emit(key, value) 返回键值对。

参数说明:
1. map :映射函数 (生成键值对序列,作为 reduce 函数参数)。
2. reduce 统计函数,reduce函数的任务就是将key- values变成key-value,也就是把values数组变成一个单一的值value。
3. out 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。
4. query 一个筛选条件,只有满足条件的文档才会调用map函数。(query。limit,sort可以随意组合)
5. sort 和limit结合的sort排序参数(也是在发往map函数前给文档排序),可以优化分组机制
6. limit 发往map函数的文档数量的上限(要是没有limit,单独使用sort的用处不大)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

//测试数据准备

db.user.drop();

 

for(var i=10; i< 100; i++) {

   db.user.insert({

     name:"user" + i,

     age : Math.floor(Math.random()*10)+ 20,

     sex : Math.floor(Math.random()*3)%2 ==0 ? 'M' : 'F',

     chinese : Math.floor(Math.random()*50)+50,

     math : Math.floor(Math.random()*50)+50,

     english : Math.floor(Math.random()*50)+50,

     class : "C" + i%5

   })

}

 

 

// runCommand运行方式

db.sales.runCommand({

   mapreduce: "user",

 

   map: function(){

     if(this.class == "C1") {

       emit(this.age, this.age);

     }

   },

 

   reduce: function(key,values){

     var maxValue = Max(key, values);

     return maxValue;

   },

 

   {

     out: {inline: 1},

     query : "",

     sort: "",

     limit: "",

   }

})

 

 

db.user.mapReduce(

   // 映射函数,里面会调用emit(key,value),集合会按照你指定的key进行映射分组。

   function(){

     // 按照emit函数的第一个参数进行分组

     // 第二个参数的值会传递给reduce

     emit(this.age, this); 

   },

 

   // 简化函数,会对map分组后的数据进行分组简化

   // 在reduce(key,value)中的key就是emit中的key, vlaues为emit分组后的emit(value)的集合

   function(key, values){

     var maxValue = Math.max(key, values);

     return maxValue;

   },

 

   // 可选参数

   {

     query: {sex: "F"},

     out: "result",

     sort : {},

     limit : 0

   }

)

执行结果:

?

1

2

3

4

5

6

7

8

9

10

11

{

   "result" : "result", // 存放的集合名

   "timeMillis" : 23,

   "counts" : {

     "input" : 29, // 传入文档的个数

     "emit" : 29,  // 此函数被调用的次数

     "reduce" : 6, // 此函数被调用的次数

     "output" : 8  // 最后返回文档的个数

   },

   "ok" : 1

}

查看返回的结果:

?

1

db.result.find()

查看更多关于MongoDB学习笔记之MapReduce使用示例的详细内容...

  阅读:20次