regex MongoDB正则表达式查询在Java/Spring中不起作用

niknxzdl  于 2022-11-18  发布在  Go
关注(0)|答案(2)|浏览(135)

我尝试在数据库中查找菜谱,其中菜谱的标题包含方法参数中的字符串。我不希望它必须是完全匹配的(现在的方式),而是如果字符串存在于菜谱的“标题”字段中的任何地方,它就应该被认为是匹配的。这意味着如果我搜索“牛肉”,你可能会得到很多菜谱。下面是我的代码:

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".*/ }

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

我真的不知道我做错了什么。有人能看到我的错误吗?错误消息也没有真正帮助我。

4uqofj5v

4uqofj5v1#

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

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

1l5u6lss2#

这可以通过删除斜杠来实现。

String titleRegex = String.format(".*%s.*", title);

@Query("{'title': { $regex: ?0 }}")
public List<Recipe> findByTitleLike(String titleRegex);

参考:https://www.mongodb.com/community/forums/t/regex-not-working-despite-following-exactly-what-the-documentation-says/9073

相关问题