這篇文章主要介紹了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的用處不大)
- //測試數據準備
- 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
- }
- )
執行結果:
- {
- "result" : "result", // 存放的集合名
- "timeMillis" : 23,
- "counts" : {
- "input" : 29, // 傳入文檔的個數
- "emit" : 29, // 此函數被調用的次數
- "reduce" : 6, // 此函數被調用的次數
- "output" : 8 // 最后返回文檔的個數
- },
- "ok" : 1
- }
查看返回的結果:
- db.result.find()
|
新聞熱點
疑難解答