Mongodb 的中數據統計神器Map_Reduce的使用

Map -reduce 就是先把數據拆分然後合併的的一種思想,在map 方法中至少要調用一次內置函數emit,該函數需要兩個參數,第一個是參數key,可以理解爲關係數據庫中的group by 的字段,第二個參數是value,也就是要進行聚合操作的字段。emit 的作用是根據key ,把value組合爲一個數組,爲reduce提供輸入參數值。執行reduce 處理,需要用兩個參數,第一個參數是key 第二個參數是value數組,也就是上一步中產生的結果。在這個函數裏進行聚合處理,並返回處理後的對象,對上一步的結果進行finalize處理。把結果輸出到out指定的目標(v1.7 以上版本可以指定out{inline :1}直接返回結果集)例如:
db.users.mapReduce(m, r, {out : {inline : 1}})
MongoDB中使用emit函數向MapReduce提供Key/Value對。Reduce函數接受兩個參數:Key,emits. Key即爲emit函數中的Key。 emits是一個數組,它的元素就是emit函數提供的Value。Reduce函數的返回結果必須要能被Map或者Reduce重複使用,所以返回結果必須與emits中元素結構一致。Map或者Reduce函數中的this關鍵字,代表當前被Mapping文檔。

map = %Q{
        function(){
          emit({userinfo_id:this.userinfo_id,customer_id:this.customer_id},{paycost:this.paycost})
        }
      }
      reduce = %Q{
        function(key,values){
          var res={order_count:0,order_amount:0.0}
          values.forEach(function(val){
              res.order_count += 1;
              if(!isNaN(val.paycost) && val.paycost!=""){
                  res.order_amount = res.order_amount +parseFloat(val.paycost);
              }
          });
          return res;
        }
      }
      results = OrderStateChange.where({'customer_id'=>analyse_infos[:customer_id],'userinfo_id'=>analyse_infos[:userinfo_id],'state'=>{'$in' => ['receive','completed']}}).map_reduce(map, reduce).out(inline: true)

這種操作最終將會按照我們設定的方式返回的信息{_id:{userinfo_id:“121212”,customer_id:“23322”},value:{paycost:30}}
map中的參數的其實就是爲reduce 提供(key ,value),key 和value都是可以封裝多個參數的如emit({userinfo_id:this.userinfo_id,customer_id:this.customer_id},{paycost:this.paycost})這個emit中的key 就是{userinfo_id:this.userinfo_id,customer_id:this.customer_id},value就是{paycost:this.paycost}。mongodb 中MR的使用可以非常大的提升數據的查詢和統計速度。真是屢試不爽

發佈了43 篇原創文章 · 獲贊 20 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章