sha*_*ayy 8 spring mongodb spring-data spring-data-mongodb
这是我的文件:
@Document(collection = "posts")
public class Post {
@Id
String id;
String title;
String description;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用like运算符查询带有标题或说明的帖子.我的存储库
public class PostsRepository extends MongoRepository<Post, String> {
@Query(value = "{ $or: [ { 'title' : ?0 }, { 'description' : ?0 } ] }")
Page<Post> queryByTitleOrDescription(String query, Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)
如何使用LIKE在两个字段之间或之间执行此查询?
Oli*_*ohm 11
如果需要,您甚至可以不使用任何显式查询声明:
interface PostRepository extends Repository<Post, String> {
// A default query method needs parameters per criteria
Page<Post> findByTitleLikeOrDescriptionLike(String title,
String description,
Pageable pageable);
// With a Java 8 default method you can lipstick the parameter binding
// to accept a single parameter only
default Page<Post> findByTitleOrDescription(String candidate, Pageable pageable) {
return findByTitleLikeOrDescriptionLike(candidate, candidate, pageable);
}
}
Run Code Online (Sandbox Code Playgroud)
所以回答我自己的问题,这是我提出的解决方案,如果有人知道更高效的东西,我会很感激(我认为文本搜索不适用,因为它不适用于部分单词)
@Query(value = "{ $or: [ { 'title' : {$regex:?0,$options:'i'} }, { 'description' : {$regex:?0,$options:'i'} } ] }")
Page<Post> query(String query, Pageable page);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10241 次 |
| 最近记录: |