【问题标题】:MongoDB regular expression query not working in Java/SpringMongoDB 正则表达式查询在 Java/Spring 中不起作用
【发布时间】:2019-08-29 11:16:00
【问题描述】:

我正在尝试在其标题包含方法参数中的字符串的数据库中查找食谱。我不希望它必须完全匹配(现在的方式),但是如果字符串存在于配方的“标题”字段中的任何位置,则应将其视为匹配。这意味着如果我正在搜索“牛肉”,您可能会期望得到很多食谱。这是我的代码:

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface RecipeRepository extends MongoRepository<Recipe, String> {

    public Recipe findByTitle(String title);

    //@Query("{ 'title': /.*?0.*/ }")
    @Query("{ 'title' : ?0 }")
    public List<Recipe> findByTitleLike(String title);

} 

该代码目前可与 ?0 占位符一起使用,并找到与标题完全匹配的匹配项。你可以看到我上面用正则表达式注释掉的行,我试图匹配 title 参数两侧的任何内容,所以基本上如果它存在于标题中,它应该匹配。

我按照这个答案构造了正则表达式查询:https://stackoverflow.com/a/3305687/8887398

我还查看了文档:https://docs.mongodb.com/manual/reference/operator/query/regex/

我在运行代码时不断收到此错误:

Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'recipeRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
{ 'title': /.*"_param_0".*/ }

有一个小箭头指向字符串中的特定位置,不确定是否相关:

我真的不确定我做错了什么。谁能看到我的错误?错误消息也没有真正帮助我。

【问题讨论】:

  • 看起来你不能使用正则表达式文字,使用字符串文字,'title': '.*"_param_0".*'
  • @WiktorStribiżew 它可以编译但不起作用。我试过这个:@Query("{ 'title': '.*?0.*' }"),如果看起来正确的话。我收到错误:“JSON 字符串中的文件结尾。”,有什么想法吗?
  • 试试@Query("{ \"title\": \".*?0.*\" }"
  • @WiktorStribiżew 不幸的是,它现在是相同的原始 JSONParseException 错误。我也将 ) 添加到您的查询末尾。

标签: java regex spring mongodb


【解决方案1】:

您很可能已经找到了解决方案,但对于那些仍在寻找的人:

@Query('title':'.\*?0.\*')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多