我正在尝试为我的网站实现map reduce(使用MongoDB 3.0,Java 7)。
为了让我开始,我只想测试功能,但我的收藏不受其输出的影响:
String map = "function(){"
+ "emit(\"testValue\", [5, 5, 10]);"
+ "}" ;
String reduce = "function(key, values){"
+ "return Array.sum(values);"
+ "}";
// INPUT COLLECTION
MongoCollection<Document> collection =
MongoDBManager.getMongoCollection("colTest");
// OUTPUT COLLECTION
MongoCollection<Document> index =
MongoDBManager.getMongoCollection("index");
// MAP REDUCE
collection.mapReduce(map, reduce)
.action(MapReduceAction.REPLACE)
.collectionName("index");
// SEE CONTENT OF INDEX
FindIterable<Document> result = index.find();
MongoCursor<Document> cursor = result.iterator();
while(cursor.hasNext()){
Document current = cursor.next();
System.out.println(current.toString());
}
cursor.close();
这是println的输出:
Document{{_id=58f4098537a734176b1c140f, testID=0}}
colTest不为空。这是一个示例:
{"messages": [
{
"date": 1492308383230,
"likesNumber": 1,
"_id": {"$oid": "58f2d19f37a734176941a0ef"},
"likers": ["allen"],
"content": "a",
"username": "paul"
},
{
"date": 1492308345420,
"likesNumber": 0,
"_id": {"$oid": "58f2d17937a734172897ea8b"},
"content": "ab",
"username": "allen"
},
{
"date": 1492308287884,
"likesNumber": 0,
"_id": {"$oid": "58f2d13f37a73416ef3d214e"},
"content": "abc",
"username": "john"
}
]}
我想要以下输出......
{"testValue" : 20}
...在colTest中有很多次文件(我的样本中有3个)。
为什么我的收藏品保持不变?代码中是否有问题,或者我应该期待这个结果?
答案 0 :(得分:2)
您可以尝试以下MapReduce查询。
String map = "function() {\n" +
" var array = [5, 5, 10];\n" +
" for (var idx = 0; idx < array.length; idx++) {\n" +
" var key = 'testValue';\n" +
" var value = array[idx];\n" +
" emit(key, value);\n" +
" }\n" +
" };";
String reduce = "function(key, values) {return Array.sum(values);};";
// MAP REDUCE
collection.mapReduce(map, reduce).action(MapReduceAction.REPLACE).collectionName("index").first();
first
表示驱动程序运行查询。
这将输出类似
的内容Document{{_id=testValue, value=20.0}}