【问题标题】:Spring Data MongoDB Repositories Query multiple fieldsSpring Data MongoDB Repositories 查询多个字段
【发布时间】:2016-01-08 10:52:04
【问题描述】:

这是我的文件:

@Document(collection = "posts")
public class Post {
    @Id
    String id;
    String title;
    String description;
}

我正在尝试使用 like 运算符查询带有标题或描述的帖子。 我的仓库

public class PostsRepository extends MongoRepository<Post, String> {
    @Query(value = "{ $or: [ { 'title' : ?0 }, { 'description' : ?0 } ] }")
    Page<Post> queryByTitleOrDescription(String query, Pageable pageable);
}

我如何使用 LIKE 在两个字段之间执行此查询?

【问题讨论】:

    标签: spring mongodb spring-data spring-data-mongodb


    【解决方案1】:

    如果需要,您甚至可以不使用任何明确的查询声明:

    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);
      }
    }
    

    【讨论】:

    【解决方案2】:

    所以回答我自己的问题,这是我想出的解决方案,如果有人知道性能更高的东西,我会很感激(我相信文本搜索不适用,因为它不适用于部分单词)

    @Query(value = "{ $or: [ { 'title' : {$regex:?0,$options:'i'} }, { 'description' : {$regex:?0,$options:'i'} } ] }")
        Page<Post> query(String query, Pageable page);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-10
      • 2018-07-13
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2016-04-19
      • 2017-12-03
      • 2013-03-14
      • 1970-01-01
      相关资源
      最近更新 更多