Spring数据MongoDB存储库查询多个字段
Spring Data MongoDB Repositories Query multiple fields
这是我的文档:
@Document(collection = "posts")
public class Post {
@Id
String id;
String title;
String description;
}
我正在尝试使用类似运算符查询带有标题或描述的帖子。
我的存储库
public class PostsRepository extends MongoRepository<Post, String> {
@Query(value = "{ $or: [ { 'title' : ?0 }, { 'description' : ?0 } ] }")
Page<Post> queryByTitleOrDescription(String query, Pageable pageable);
}
如何在两个字段上使用 LIKE 执行查询?
因此,为了回答我自己的问题,这是我想出的解决方案,如果有人知道性能更高的东西,我将不胜感激(我认为文本搜索不适用,因为它不适用于部分词)
@Query(value = "{ $or: [ { 'title' : {$regex:?0,$options:'i'} }, { 'description' : {$regex:?0,$options:'i'} } ] }")
Page<Post> query(String query, Pageable page);
}
如果需要,您甚至可以不使用任何显式查询声明:
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);
}
}
这是我的文档:
@Document(collection = "posts")
public class Post {
@Id
String id;
String title;
String description;
}
我正在尝试使用类似运算符查询带有标题或描述的帖子。 我的存储库
public class PostsRepository extends MongoRepository<Post, String> {
@Query(value = "{ $or: [ { 'title' : ?0 }, { 'description' : ?0 } ] }")
Page<Post> queryByTitleOrDescription(String query, Pageable pageable);
}
如何在两个字段上使用 LIKE 执行查询?
因此,为了回答我自己的问题,这是我想出的解决方案,如果有人知道性能更高的东西,我将不胜感激(我认为文本搜索不适用,因为它不适用于部分词)
@Query(value = "{ $or: [ { 'title' : {$regex:?0,$options:'i'} }, { 'description' : {$regex:?0,$options:'i'} } ] }")
Page<Post> query(String query, Pageable page);
}
如果需要,您甚至可以不使用任何显式查询声明:
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);
}
}