如何在Spring Boot中编写Elastic Search Count API?含CountRequest用法及代码示例
在Spring Boot中实现Elasticsearch Count API(基于CountRequest)
前提准备
首先确保Spring Boot项目引入与Elasticsearch集群版本匹配的高级REST客户端依赖,以Maven为例:
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.17.9</version> <!-- 版本需和你的ES集群一致 --> </dependency>
同时在application.yml配置ES连接信息:
elasticsearch: host: localhost port: 9200 username: elastic password: your-password
配置RestHighLevelClient
创建配置类注入客户端实例:
import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.apache.http.HttpHost; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.client.BasicCredentialsProvider; @Configuration public class ElasticsearchConfig { @Value("${elasticsearch.host}") private String host; @Value("${elasticsearch.port}") private int port; @Value("${elasticsearch.username}") private String username; @Value("${elasticsearch.password}") private String password; @Bean public RestHighLevelClient restHighLevelClient() { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( org.apache.http.auth.AuthScope.ANY, new UsernamePasswordCredentials(username, password) ); return new RestHighLevelClient( org.elasticsearch.client.RestClient.builder( new HttpHost(host, port, "http")) .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) ); } }
使用CountRequest实现文档计数
1. 统计整个索引的文档总数
直接创建指定索引的CountRequest,执行后获取总数:
import org.elasticsearch.action.count.CountRequest; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class EsCountService { private final RestHighLevelClient client; public EsCountService(RestHighLevelClient client) { this.client = client; } public long getTotalDocumentCount(String indexName) throws IOException { CountRequest countRequest = new CountRequest(indexName); CountResponse countResponse = client.count(countRequest); return countResponse.getCount(); } }
2. 带查询条件的文档计数
如果需要统计符合特定条件的文档,比如status字段为active的文档,结合QueryBuilder实现:
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; public long getFilteredDocumentCount(String indexName) throws IOException { CountRequest countRequest = new CountRequest(indexName); // 构造查询条件:匹配status=active的文档 TermQueryBuilder queryBuilder = QueryBuilders.termQuery("status", "active"); countRequest.query(queryBuilder); CountResponse countResponse = client.count(countRequest); return countResponse.getCount(); }
3. 暴露HTTP接口(Controller示例)
将计数服务封装成API接口:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController @RequestMapping("/api/es") public class EsCountController { private final EsCountService countService; public EsCountController(EsCountService countService) { this.countService = countService; } @GetMapping("/count/{index}") public long getTotalCount(@PathVariable String index) throws IOException { return countService.getTotalDocumentCount(index); } @GetMapping("/count/active/{index}") public long getActiveCount(@PathVariable String index) throws IOException { return countService.getFilteredDocumentCount(index); } }
关键注意事项
- 版本兼容:客户端版本必须与Elasticsearch集群版本完全一致,否则会出现兼容性问题。
- 异常处理:实际项目中不要直接抛出
IOException,建议捕获后封装为自定义业务异常。 - 性能优化:全量计数是轻量级操作,但超大索引下避免频繁执行,可考虑缓存结果或使用
_cat/countAPI。
内容的提问来源于stack exchange,提问作者Kunal Gupta
相关产品推荐
相关产品推荐

