[英]mongodb mapreduce script to count total orders fails
我是mongodb的新手,並且正計划從SQL遷移到noSQL。 我存儲了很多proc,我認為mapReduce是noSQL世界中的“等效”對象。 我從一個js腳本開始,該腳本試圖按客戶計數訂單,但是它給出了錯誤的結果。 腳本是:
db = connect("localhost:27017/pgi");
for(i=0;i<1000;i++){
db.orders.insert(
{
"cust_id" : 1,
"total" : 100,
});
}
for(i=0;i<1000;i++){
db.orders.insert(
{
"cust_id" : 2,
"total" : 100,
});
}
var res = db.orders.find({cust_id : 1});
print("Total Orders for customer 1:" + res.count());
var res = db.orders.find({cust_id : 2});
print("Total Orders for customer 2:" + res.count());
//map reduce
var map = function(){
emit(this.cust_id, 1);
}
var reduce = function(key, values){
var c = 0;
for (index in values) {
c += 1;
}
return {cust_id : key, count: c};
}
var res = db.orders.mapReduce(
map,
reduce,
{
out : {inline : 1}
}
);
res.find({}).forEach(function(item){
printjson(item);
});
每個客戶的預期輸出是1000,但是我得到了:
connecting to: test
connecting to: localhost:27017/pgi
Total Orders for customer 1:1000
Total Orders for customer 2:1000
{ "_id" : 1, "value" : { "cust_id" : 1, "count" : 101 } }
{ "_id" : 2, "value" : { "cust_id" : 2, "count" : 101 } }
有人可以告訴我出什么問題了。 問候,
使用MapReduce,reducer的輸出格式必須與mapper輸出值的格式相同,因為reducer可能針對同一鍵多次運行。 同樣,化簡器不需要輸出鍵,只需輸出在對輸入數組執行任何操作后的結果值。
因此,在您的情況下,映射器看起來正確,可以按客戶計數訂單,但減速器應僅輸出總計數,而不是生成具有鍵和計數的Object。
精簡器還需要對每個index
的值求和,而不是加1,以處理它在化簡函數的先前調用的輸出上進行操作的情況。
var reduce = function(key, values){
var c = 0;
for (var index in values) {
c += values[index];
}
return c;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.