gpt4 book ai didi

java - MongoDB 的reduce-phase 没有按预期工作

转载 作者:行者123 更新时间:2023-11-30 03:59:13 27 4
gpt4 key购买 nike

我使用了 MongoDB 中的 mapReduce 编程的 java 教程,最终得到了以下代码:

package mapReduceExample;

import com.mongodb.BasicDBObject;
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 MapReduceExampleMain {

/**
* @param args
*/
public static void main(String[] args) {

Mongo mongo;

try {
mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("library");

DBCollection books = db.getCollection("books");

BasicDBObject book = new BasicDBObject();
book.put("name", "Understanding JAVA");
book.put("pages", 100);
books.insert(book);

book = new BasicDBObject();
book.put("name", "Understanding JSON");
book.put("pages", 200);
books.insert(book);

book = new BasicDBObject();
book.put("name", "Understanding XML");
book.put("pages", 300);
books.insert(book);

book = new BasicDBObject();
book.put("name", "Understanding Web Services");
book.put("pages", 400);
books.insert(book);

book = new BasicDBObject();
book.put("name", "Understanding Axis2");
book.put("pages", 150);
books.insert(book);

String map = "function()"
+ "{ "
+ "var category; "
+ "if ( this.pages > 100 ) category = 'Big Books'; "
+ "else category = 'Small Books'; "
+ "emit(category, {name: this.name});"
+ "}";

String reduce = "function(key, values)"
+ "{"
+ "return {books: values.length};"
+ "} ";

MapReduceCommand cmd = new MapReduceCommand(books, map, reduce,
null, MapReduceCommand.OutputType.INLINE, null);

MapReduceOutput out = books.mapReduce(cmd);

for (DBObject o : out.results()) {
System.out.println(o.toString());
}

//aufräumen
db.dropDatabase();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}
}

这是一个非常简单的减少阶段,但它不是我想要的:(

输出为:

{ "_id" : "Big Books" , "value" : { "books" : 4.0}}
{ "_id" : "Small Books" , "value" : { "name" : "Understanding JAVA"}}

我希望这样:

{ "_id" : "Big Books" , "value" : { "books" : 4.0}}
{ "_id" : "Small Books" , "value" : { "books" : 1.0}}

为什么在小书的情况下,reduce-Phase不返回values.length?

你好,安德烈

最佳答案

因为如果只有一个结果,那么reduce就永远不会运行。将其更改为终结函数或其他东西。

关于java - MongoDB 的reduce-phase 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22353605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com