在Javascript中迭代地将数组元素传递给mapReduce

时间:2013-11-18 04:57:44

标签: javascript arrays mapreduce

我正在尝试将关键字数组的元素传递给我的mapper函数。这样做的目的是计算关键字出现的文档数量。我收到一个错误,说明在mapper函数中没有定义单词数组。当我有mapper函数emit(words [i],1)时,它不知道单词[i]是什么。我该如何处理这个问题?这是我的代码

db = db.getSiblingDB('hw4') //this is the database I'm working with
words = ['kinda','Scott']; //these are my keywords
var mapper = function() { //if searching for 'kinda', I want this function to emit (kinda, 1). This is not working
    emit( words[i], 1);          
};

var reducer = function(key, values) {
    return Array.sum(values) //this sums all of the ones and thereby gets the total # of docs that contain the keyword
};


for (var i=0; i<words.length;i++) { //here I'm iterating over the words array
result = db.messages.mapReduce(mapper,
                               reducer,
                               {
                                   out: { merge: 'keywordCollectiontest'}, //the results of each mapReduce are added to this collection
                                   query: {msg: {$regex: words[i]}} //this returns only the docs that contain words[i]
                               }
)
    printjson(result) //this simply shows information about how the mapReduce went
}

我得到的错误是这个:

$ mongo fifthMapReduce.js
MongoDB shell version: 2.4.7
connecting to: test
Sun Nov 17 20:27:50.017 map reduce failed:{
"errmsg" : "exception: ReferenceError: words is not defined near 'emit( words[i], 1)'  (line 2)",
"code" : 16722,
"ok" : 0
} at src/mongo/shell/collection.js:970
failed to load: fifthMapReduce.js

所以我得到的确切错误是:

"errmsg" : "exception: ReferenceError: words is not defined near 'emit( words[i], 1)'  (line 2)"

感谢您的帮助。

0 个答案:

没有答案