gpt4 book ai didi

java - Spring 数据 mongodb : Text search for 'phrase OR words in phrase'

转载 作者:行者123 更新时间:2023-12-02 17:32:43 27 4
gpt4 key购买 nike

我需要在名为 blog 的集合中搜索文档,该集合具有为标题、标签、摘要和正文定义的文本索引:

@Document(collection="blog")
public class Blog {
@Id
private String id;
@TextIndexed(weight = 10)
private String title;
@TextIndexed(weight = 9)
private String tags;
@TextIndexed(weight = 8)
private String summary;
@TextIndexed(weight = 7)
private String body;
@TextScore
private Float score;

//getters and setters
}

现在,我需要根据以下条件对 blog 集合执行文本搜索:

  1. 检查用户输入是否包含多个单词。
  2. 如果 searchKey 是单个单词,则执行文本搜索并返回根据权重排序的响应。
  3. 如果 searchKey 包含多个单词,则执行搜索完整的 PHRASE 或 PHRASE 中的任何单词。

对于第二种情况,TextCriteria 定义如下:

TextCriteria criteria = TextCriteria.forDefaultLanguage().matching("SingleWord");

对于第3种情况,如何在单个查询中为组合编写条件定义:

query 1: db.articles.find( { $text: { $search: "\"coffee cake\"" } } ) //phrase search
query 2: db.articles.find( { $text: { $search: "coffee cake" } } ) //word search

我可以用

执行搜索吗
query 1 OR query 2 with sorted result based on score.

对于完整短语匹配的结果,分数应该更高。

最佳答案

Spring Data MongoDB 支持以下文本搜索操作:

  • TextCriteria.forDefaultLanguage().matchingAny("search term1", "search term2")
  • TextCriteria.forDefaultLanguage().matching("搜索词")
  • TextCriteria.forDefaultLanguage().matchingPhrase("搜索词")

第一个条件可以执行文本搜索:search、text1 和 text2第二个条件可以执行文本搜索:search, term第三个条件是短语搜索:'search term'

可以使用上述条件形成文本查询:

Query query = TextQuery.queryText(TextCriteria.forDefaultLanguage().matchingAny("search term").sortByScore().with(new PageRequest(pageNum, docCount, new Sort(new Order(Sort.Direction.DESC, "score"))));

要使用 score(文本搜索分数)进行排序,我们需要在各自的 POJO 中添加一个名为 score 的字段:

@TextScore
private Float score;

我们可以在文本查询上添加其他过滤器,如下所示:

query.addCriteria(Criteria.where("city").is("Delhi").and("country").is("India").and("price").lte(200.50).gte(100.50);

最后执行这个查询:

List<Product> products = mongoOperations.find(query, Product.class)

默认情况下,Mongodb 会为短语匹配分配更高的分数。因此,在需要分数较高的词组匹配再进行普通文本匹配的情况下,不需要先查找词组匹配。

关于java - Spring 数据 mongodb : Text search for 'phrase OR words in phrase' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30801801/

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