例2、查找订单中一个商品对应的订单总数和这个商品每个订单的平均销售数量
1、先看订单表orders的数据结构如下图
这样的数据共有6条,如下,只列出了items这个字段
2、下面给出map函数
var mapFunction2 = function() {
for (var idx = 0; idx < this.items.length; idx++) {
var key = this.items[idx].sku;
var value = {
count: 1,
qty: this.items[idx].qty
};
emit(key, value);
}
};
3、写reduce函数
var reduceFunction2 = function(keySKU, countObjVals) {
reducedVal = { count: 0, qty: 0 };
for (var idx = 0; idx < countObjVals.length; idx++) {
reducedVal.count += countObjVals[idx].count;
reducedVal.qty += countObjVals[idx].qty;
}
return reducedVal;
};
4、写finalize函数
var finalizeFunction2 = function (key, reducedVal) {
reducedVal.avg = reducedVal.qty/reducedVal.count;
return reducedVal;
};
5、执行mapReduce函数
6、查看结果