gpt4 book ai didi

java - 将 mongo search 从 runCommand 升级为使用 Java 驱动程序查找

转载 作者:行者123 更新时间:2023-12-01 12:53:39 24 4
gpt4 key购买 nike

我正在使用 Java 驱动程序来运行一些 mongo 文本搜索。我之前的代码示例是(其中值是传入的字符串):

DBCollection coll = db.getCollection("testCollection");
//create the basic object
DBObject searchCmd = new BasicDBObject();
//create the search cmd
searchCmd.put("text", "testCollection"); // the name of the collection (string)
// define the search word
searchCmd.put("search", value); // the term to search for (string)
// define the return values
searchCmd.put("project", new BasicDBObject("score", 1).append("name", 1).append("path", 0).append("_id", 0));
// get the results
BasicDBObject commandResult = db.command(searchCmd);
// Just out the results key
BasicDBList results = (BasicDBList) commandResult.get("results");

然后我循环遍历“结果”,并得到每个结果的得分

// Get the number ii
BasicDBObject element = (BasicDBObject) results.get(ii);
// Now get the score
double score = (double) element.get("score");

我想升级为使用 find,因为这似乎是 2.6 及更高版本更喜欢的方式。到目前为止我已经:

DBCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject();
query.append("$text", new BasicDBObject("$search", value));
DBCursor cursor = coll.find(query);

但是,我不知道如何获得分数。我尝试做类似的事情:

query.append("score", new BasicDBObject("$meta", "textScore"));

但这不起作用。我希望能够获取名称和分数,以便我可以将它们插入到一个也保存分数的新集合中。

我可以通过以下方式轻松获得名称:

while (cursor.hasNext()) 
{
DBObject next = cursor.next();
String name = next.get("name").toString();
}

但是我如何获得分数呢?

最佳答案

我发现了这个有趣的页面:http://api.mongodb.org/java/current/

看来 find 可以采用具有字段的第二个 DBObject。

我创建了一个新对象:

BasicDBObject fields = new BasicDBObject();
fields.append("score", new BasicDBObject("$meta", "textScore"));

我正在调用 find 使用:

DBCursor cursor = coll.find(query, fields);

现在我可以像获取名字一样获取分数。

关于java - 将 mongo search 从 runCommand 升级为使用 Java 驱动程序查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24037580/

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