springboot集成 elasticsearch8统计数量
时间: 2023-11-11 11:03:21 浏览: 133
好的,关于 springboot 集成 elasticsearch8 统计数量的问题,你可以使用 Elasticsearch 的 Count API 来实现。具体代码如下:
```
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.IndexExistsRequest;
import org.elasticsearch.client.indices.IndexExistsResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.query.QuerySearchRequest;
import org.elasticsearch.search.query.QuerySearchResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ElasticsearchService {
@Autowired
RestHighLevelClient restHighLevelClient;
public long countDocument(String indexName, String field, String value) throws IOException {
IndexExistsResponse indexExistsResponse = restHighLevelClient.indices().exists(new IndexExistsRequest(indexName), RequestOptions.DEFAULT);
if (!indexExistsResponse.isExists()) {
return 0;
}
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery(field, value));
QuerySearchRequest searchRequest = new QuerySearchRequest(indexName);
searchRequest.source(sourceBuilder);
QuerySearchResponse searchResponse = restHighLevelClient.searchQuery(searchRequest, RequestOptions.DEFAULT);
return searchResponse.getHits().getTotalHits().value;
}
}
```
这段代码中,我们使用 Elasticsearch 的 Count API 实现了对指定索引中满足条件的文档数量统计。具体实现细节可以参考注释部分。希望对你有帮助!
阅读全文