1. 使用Repository继承的方法查询文档
  2. 使用DSL语句查询文档
    ES通过json类型的请求体查询文档,方法如下:
GET /索引/_search 
{
"query":{
搜索方式:搜索参数
}
}

query后的json对象称为DSL语句,我们可以在接口方法上使用@Query注解自定义DSL语句查询。

@Query("{" +
" \"match\": {" +
" \"desc\": \"?0\"" +
" }" +
" }")
List<Product> findByProductDescMatch(String key);
@Query("{" +
" \"match\": {" +
" \"desc\": {" +
" \"query\": \"?0\"," +
" \"fuzziness\": 1" +
" }" +
" }" +
" }")
  1. 按照规则命名方法进行查询
    只需在Repository接口中按照SpringDataES的规则命名方法,该方法就能完成相应的查询。
    规则:查询方法以findBy开头,涉及查询条件时,条件的属性用条件关键字连接
    SpringDataES查询方式_java
List<Product> findByProductDescFuzzy(String key);

List<Product> findByName(String name);

List<Product> findByNameOrDesc(String name,String desc);

List<Product> findByNameAndDesc(String name,String desc);

List<Product> findByIdBetween(Integer startId,Integer endId);
  1. 分页查询
    使用继承或自定义的方法时,在方法中添加Pageable类型的参数,返回值为Page类型即可进行分页查询。
// 测试继承的方法: 
// 参数1:页数 参数2:每页条数
Pageable pageable = PageRequest.of(0,3);
Page<Product> page = repository.findAll(pageable);
System.out.println(page.getContent());
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());

// 自定义方法
Page<Product> findByProductDesc(String productDesc, Pageable pageable);
// 测试自定义方法
Pageable pageable = PageRequest.of(1,3);
Page<Product> page = repository.findByProductDesc("优秀",pageable);
System.out.println(page.getContent());
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
  1. 结果排序
    使用继承或自定义的方法时,在方法中添加Sort类型的参数即可进行结果排序。
Sort sort = Sort.by(Sort.Direction.DESC,"id");
Iterable<Product> products = repository.findAll(sort);
for (Product product:products)
System.out.println(product);