例2、查找訂單中一個商品對應的訂單總數和這個商品每個訂單的平均銷售數量
1、先看訂單表orders的資料結構如下圖
<a href="http://blog.51cto.com/attachment/201309/220556311.png" target="_blank"></a>
這樣的資料共有6條,如下,隻列出了items這個字段
<a href="http://blog.51cto.com/attachment/201309/221057627.png" target="_blank"></a>
2、下面給出map函數
1
2
3
4
5
6
7
8
9
10
<code>var</code> <code>mapFunction2 = </code><code>function</code><code>() {</code>
<code>for</code> <code>(</code><code>var</code> <code>idx = 0; idx < </code><code>this</code><code>.items.length; idx++) {</code>
<code>var</code> <code>key = </code><code>this</code><code>.items[idx].sku;</code>
<code>var</code> <code>value = {</code>
<code>count: 1,</code>
<code>qty: </code><code>this</code><code>.items[idx].qty</code>
<code>};</code>
<code>emit(key, value);</code>
<code>}</code>
3、寫reduce函數
<code>var</code> <code>reduceFunction2 = </code><code>function</code><code>(keySKU, countObjVals) {</code>
<code>reducedVal = { count: 0, qty: 0 };</code>
<code>for</code> <code>(</code><code>var</code> <code>idx = 0; idx < countObjVals.length; idx++) {</code>
<code>reducedVal.count += countObjVals[idx].count;</code>
<code>reducedVal.qty += countObjVals[idx].qty;</code>
<code>return</code> <code>reducedVal;</code>
4、寫finalize函數
<code>var</code> <code>finalizeFunction2 = </code><code>function</code> <code>(key, reducedVal) {</code>
<code>reducedVal.avg = reducedVal.qty/reducedVal.count;</code>
5、執行mapReduce函數
<a href="http://blog.51cto.com/attachment/201309/221710708.png" target="_blank"></a>
6、檢視結果
<a href="http://blog.51cto.com/attachment/201309/221808297.png" target="_blank"></a>
本文轉自shayang8851CTO部落格,原文連結:http://blog.51cto.com/janephp/1292033,如需轉載請自行聯系原作者