Mongodb3.0 java MapReduce实例

来源:互联网 发布:中学物理实验模拟软件 编辑:程序博客网 时间:2024/06/06 05:22
String mapFunction2 = "function() {  "+
                      " var key = this.userid;  "+
                      " var value = {  "+
                                   "  userid: this.userid, "+
                                   " total_time: this.length, "+
                                   " count: 1, "+
                                   " avg_time: 0 "+
                                   " }; "+


                      " emit( key, value );  "+
                 " };";

String reduceFunction2 ="function(key, values) { "+


                       " var reducedObject = {  "+
                                            "  userid: key, "+
                                             " total_time: 0, "+
                                            "  count:0, "+
                                            "  avg_time:0 "+
                                            " }; "+


                       " values.forEach( function(value) { "+
                                            "  reducedObject.total_time += value.total_time; "+
                                            "  reducedObject.count += value.count;  "+
                                        " } "+ 
                                     " ); "+
                        " return reducedObject;  "+
                    " };";

String finalizeFunction = "function (key, reducedValue) {  "+


           " if (reducedValue.count > 0) "+
              "  reducedValue.avg_time = reducedValue.total_time / reducedValue.count; "+


           "  return reducedValue; "+
         "}";
MongoCursor<Document> cursor4 =database.getCollection("sessions").find().iterator();
try {
while (cursor4.hasNext()) {
System.out.println("map1-2==="+cursor4.next().toJson());


}
} finally {
cursor4.close();
}

MongoCursor<Document> cursor5 = database.getCollection("sessions").mapReduce(mapFunction2, reduceFunction2).iterator();
try {
while (cursor5.hasNext()) {
System.out.println("map1-1==="+cursor5.next().toJson());


}
} finally {
cursor5.close();
}

Document command = new Document();
command.append("mapReduce", "sessions").append("map", mapFunction2).append("reduce", reduceFunction2).append("finalize", finalizeFunction).append("out", "myMapReduce2");
Document result2 = database.runCommand(command);
System.out.println("myMapReduce2===result "+result2.toJson());
System.out.println("myMapReduce2==== "+database.getCollection("myMapReduce2").count());
System.out.println("session_stat==== "+database.getCollection("session_stat").count());
0 0
原创粉丝点击