Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch Java API - How to get the number of documents without retrieving the documents

I need to get the number of documents in an index. not the documents themselves, but just this "how many" .

What's the best way to do that?

There is https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html. but I'm looking to do this in Java.

There also is https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/count.html, but it seems way old.

I can get all the documents in the given index and come up with "how many". But there must be a better way.

like image 486
ash__999 Avatar asked Jun 07 '17 20:06

ash__999


1 Answers

Use the search API, but set it to return no documents and retrieve the count of hits from the SearchResponse object it returns.

For example:

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();
like image 138
evanjd Avatar answered Sep 19 '22 20:09

evanjd