【问题标题】:Is there an exists method for any attribute in the index是否存在索引中任何属性的存在方法
【发布时间】:2021-02-16 00:58:16
【问题描述】:

索引中的任何属性是否有exists方法,我们有一个方法来检查它是否通过ID存在。我们如何构建一个抽象来检查一个实体是否存在使用不同的属性。

https://docs.spring.io/spring-data/elasticsearch/docs/current/api/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.html#existsById-ID-

【问题讨论】:

  • 对文档的给定字段进行术语(完全匹配)查询有什么区别?
  • Ping @Rpj,有输入吗?

标签: elasticsearch spring-data-elasticsearch


【解决方案1】:

假设您有一个名为 Student 的类作为您的域类,并且您将存储库定义如下:

public interface StudentRepository extends CrudRepository<Student, String> {
}

要使用自定义功能丰富StudentRepository,您必须首先为自定义功能定义一个片段接口和一个实现(实现类名称必须与接口存储库名称完全相同,并以“Impl”结尾),如如下:

public interface CustomizedStudentRepository {
  boolean existsByField(String key, Object value);
}

然后,您必须为您的自定义存储库提供一个实现:

public class CustomizedStudentRepositoryImpl {
  
  @Autowired
  private final RestHighLevelClient client;

  boolean existsByField(String key, Object value) {
      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      searchSourceBuilder
          .query(QueryBuilders.matchQuery(key, value));
      SearchRequest request = new SearchRequest(indexName);
      request.source(searchSourceBuilder);
      try {
        SearchResponse searchResponse = client.search(request, 
            RequestOptions.DEFAULT);
        long totalHits = searchResponse.getHits().getTotalHits().value;
        return totalHits > 0;
     } catch(IOException ioException) {
         // log exception
     }
     return false;
  }
}

然后重构您的StudentRepository 如下:

interface StudentRepository extends CrudRepository<Student, String>, CustomizedStudentRepository {
}

更多documentation.

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 2015-04-19
    • 2013-05-19
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多