Elasticsearch: Get Document Counts using Java High Level Rest Client
We can use Java High Level Rest Client to get the count of documents in an index. It can also be used to execute a query and get the count of matching documents.
Introduction
The Elasticsearch Java High Level Rest Client provides count API
which can be used to get the followings:
- Total number of documents in the indices or
- Number of documents matching a query.
Query Building
In our previous post we used account data and inserted in accounts
index. I want to know the number of documents where the first name of the account holder is Kelley. The following code shows the JSON
query for the same:
#Number of accounts with Firstname as Kelley
POST accounts/_count
{"query":{"match":{"firstname.keyword":"Kelley"}}}
For achieving the same using Java High Level Rest Client, we can build the query as shown below:
final var countRequest = new CountRequest("accounts");
countRequest.query(QueryBuilders.matchQuery("firstname.keyword", "Kelley"));
Query Execution
After this we can use High Level Rest Client to execute the query as following. For configuring the client please follow this post.
final var countResponse = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
final var count = countResponse.getCount();
A working code example is present in this git repository. I hope it is useful for you. Happy learning :).
References
- https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.12/java-rest-high-count.html
- https://pixabay.com/vectors/hand-counting-fingers-one-two-162127/
Comments