首先我使用Windows XP 32位操作系統,MongoDB作爲NoSQL DB和Eclipse作爲編輯器程序。我從我的學校得到了關於MapReduce的任務,因此我決定使用mapreduce查找多少工作年齡和非工作人口。我用這個代碼來輸入數據,並保存爲Insert.java:我在MongoDB中使用MapReduce時遇到了錯誤
package mongox;
import com.mongodb.BasicDBObject;
import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
public class Insert {
public static void main(String[] args) {
try{
Mongo mongox = new Mongo();
DB db = mongox.getDB("DBPublic");
DBCollection koleksi = db.getCollection("lancestorvalley");
BasicDBObject object = new BasicDBObject();
object = new BasicDBObject();
object.put("NIK", "7586930211");
object.put("Name", "Richard Bou");
object.put("Sex", "M");
object.put("Age", "31");
object.put("Blood", "A");
object.put("Status", "Married");
object.put("Education", "Bachelor degree");
object.put("Employment", "Labor");
koleksi.insert(object);
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
我使用此代碼爲MapReduce和保存爲Mapreduce.java:
package mongox;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MapReduceCommand;
import com.mongodb.MapReduceOutput;
import com.mongodb.Mongo;
public class Mapreduce {
public static void main(String[] args) {
try{
Mongo mongox = new Mongo("localhost", 27017);
DB db = mongox.getDB("DBPublic");
DBCollection koleksi = db.getCollection("lancestorvalley");
String map = "function() { "+
"var category; " +
"if (this.Age >= 15 && this.Age <=59) "+
"category = 'Working-Age Population'; " +
"else " +
"category = 'Non-Working-Age Population'; "+
"emit(category, {Nama: this.Nama});}";
String reduce = "function(key, values) { " +
"var sum = 0; " +
"values.forEach(function(doc) { " +
"sum += 1; "+
"}); " +
"return {data: sum};} ";
MapReduceCommand cmd = new MapReduceCommand(koleksi, map, reduce,
null, MapReduceCommand.OutputType.INLINE, null);
MapReduceOutput out = koleksi.mapReduce(cmd);
for (DBObject o : out.results()) {
System.out.println(o.toString());
}
}
catch(Exception e){
e.printStackTrace();;
}
}
}
我已經輸入5000個數據,當我運行Mapreduce.java的輸出是:
{ "_id" : "Non-Working-age population" , "value" : { "data" : 41.0}}
{ "_id" : "Working-age Population" , "value" : { "data" : 60.0}}
我的代碼在Mapreduce.java中有什麼問題嗎?爲什麼輸出結果只有數據大約是5000? 希望有人能幫助我,謝謝面前的傢伙
這會更好用聚合完成。查看[reduce function requirements](http://docs.mongodb.org/manual/reference/command/mapReduce/#mapreduce-reduce-cmd)。 Map/reduce可以在同一個鍵上多次運行reduce函數,並且需要一個數組作爲值。 – wdberkeley 2014-09-15 15:49:00