【发布时间】:2010-12-13 15:26:53
【问题描述】:
我想计算一个集合中我的文档(包括嵌入的)的所有键。 首先,我编写了一个 Java 客户端来解决这个问题。显示结果不到 4 秒。 然后我写了一个 map/reduce 函数。结果很好,但运行该功能需要 30 多秒! 我认为 map/reduce 函数会更快,因为它是在服务器端执行的。 Java 客户端需要从服务器获取每个文档,但速度要快得多。 为什么会这样?
//这是我的地图功能:
map = function(){
for(var key in this) {
emit(key, {count:1});
if(isNestedObject(this[key])){
m_sub(key, this[key]);
}
}
}
//这是我的reduce函数:
reduce = function (key, emits) {
total = 0;
for (var i in emits) {
total += emits[i].count;
}
return {count:total};
}
//这里是对mapreduce的调用:
mr = db.runCommand({"mapreduce":"keyword", "map" : map, "reduce" : reduce,
"scope":{
isNestedObject : function (v) {
return v && typeof v === "object";
},
m_sub : function(base, value) {
for(var key in value) {
emit(base + "." + key, {count:1});
if(isNestedObject(value[key])){
m_sub(base + "." + key, value[key]);
}
}
}
}
})
//这里是输出:
{
"result" : "tmp.mr.mapreduce_1292252775_8",
"timeMillis" : 39087,
"counts" : {
"input" : 20168,
"emit" : 986908,
"output" : 1934
},
"ok" : 1
}
//这是我的Java客户端:
public static Set<String> recursiv(DBObject o){
Set<String> keysIn = o.keySet();
Set<String> keysOut = new HashSet<String>();
for(String s : keysIn){
Set<String> keys2 = new HashSet<String>();
if(o.get(s).getClass().getSimpleName().contains("Object")){
DBObject o2 = (DBObject) o.get(s);
keys2 = recursiv(o2);
for(String s2 : keys2){
keysOut.add(s + "." + s2);
}
}else{
keysOut.add(s);
}
}
return keysOut;
}
public static void main(String[] args) throws Exception {
final Mongo mongo = new Mongo("xxx.xxx.xxx.xxx");
final DB db = mongo.getDB("keywords");
final DBCollection keywordTable = db.getCollection("keyword");
Multiset<String> count = HashMultiset.create();
long start = System.currentTimeMillis();
DBCursor curs = keywordTable.find();
while(curs.hasNext()){
DBObject o = curs.next();
Set<String> keys = recursiv(o);
for(String s : keys){
count.add(s);
}
}
long end = System.currentTimeMillis();
long duration = end - start;
System.out.println(new SimpleDateFormat("mm:ss:SS").format(Long.valueOf(duration)));
System.out.println("duration:" + duration + " ms");
//System.out.println(count);
System.out.println(count.elementSet().size());
}
//这里是输出:
00:03:726
duration:3726 ms
1898
不必担心结果数量不同(1934 年与 1898 年)。这是因为 map reduce 还计算了数组中的键,这些键不被 java 客户端计算在内。 感谢您阐明不同的执行时间。
【问题讨论】:
标签: java performance mongodb mapreduce