soputasmile
soputasmile

Reputation: 3

High level rest client get only hits' size

i know with transport client can get hits' count like this:

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

SearchResponse response = client.prepareSearch("your_index_goes_here")
.setTypes("YourTypeGoesHere")
.setQuery(QueryBuilders.termQuery("some_field", "some_value"))
.setSize(0) // Don't return any documents, we don't need them.
.get();

SearchHits hits = response.getHits();
long hitsCount = hits.getTotalHits();

but how can i get hits' size with high level rest client?

Upvotes: 0

Views: 2928

Answers (3)

Ciaran George
Ciaran George

Reputation: 613

Another potential solution is to use the aggregation builder and get the count that way.

sourceBuilder.aggregation(AggregationBuilders.count("totalCount").field("id"));

As you can see you can base it on the ID or any other unique value that would give you a total count of all fields based on the query you send.

Upvotes: 0

raspacorp
raspacorp

Reputation: 5307

If you are using Elasticsearch 6.6 or newer. Maybe you want to use the Count API: https://www.elastic.co/guide/en/elasticsearch/reference/6.6/search-count.html

In high level rest client (https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.6/java-rest-high-count.html):

CountRequest countRequest = new CountRequest("your_index_goes_here");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("some_field", "some_value"));
countRequest.source(searchSourceBuilder);

CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
long hitsCount = countResponse.getCount();

Upvotes: 1

martin-g
martin-g

Reputation: 17513

Here is a version with the REST client:

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
   .query(queryBuilder)
   .size(1);
SearchRequest searchRequest = new SearchRequest("your_index_goes_here");
searchRequest.source(searchSourceBuilder);
SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("Total: " + response.getResponse().getHits().totalHits);

Upvotes: 0

Related Questions