【问题标题】:How to properly do a case insensitive search in Java / Spring如何在 Java / Spring 中正确进行不区分大小写的搜索
【发布时间】:2022-08-14 23:59:57
【问题描述】:

我收到来自 Atlas Mongo 的警告说:

使用不区分大小写的索引时不要使用 $regex 运算符 您的查询。 $regex 实现不支持排序规则,并且 不能使用不区分大小写的索引。相反,我们推荐 Atlas 使用 $search 聚合管道阶段的搜索查询。

来源:https://www.mongodb.com/docs/atlas/schema-suggestions/case-insensitive-regex/

在我的 Java 代码中,我正在使用这个:

import org.springframework.data.mongodb.core.query.Criteria;

Criteria criteria = new Criteria();
...
criteria.and(\"search\").regex(data.getText(), \"i\"); // i means case-insensitive
...
return Query.query(criteria);

显然,当我收到警告时,这是缓慢的表现。如何应用排序规则?

什么是最好的性能方法,所以我从正则表达式中删除了 i 选项?

    标签: java spring mongodb


    【解决方案1】:

    使用不区分大小写选项查询数据的最佳做法是使用文本索引和搜索运算符而不是正则表达式

    为要查询的字段创建不区分索引大小写的索引:

    TextIndexDefinition textIndex = new TextIndexDefinitionBuilder()
      .onField("title", 2F)
      .onField("content")
      .build();
    
    MongoTemplate template = … // obtain MongoTemplate
    template.indexOps(CookingRecipe.class).ensureIndex(textIndex);
    

    然后使用文本索引查询数据:

    TextCriteria criteria = TextCriteria.forDefaultLanguage()
      .matchingAny("coffee", "cake");
    
    Query query = TextQuery.queryText(criteria)
      .sortByScore()
      .with(new PageRequest(0, 5)); //top 5 documents matching “coffee” or “cake”
    

    请参考$text $search your Documents with Spring Data MongoDB 了解更多信息

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2015-09-02
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2021-02-18
      相关资源
      最近更新 更多