GrahamGoudeau
GrahamGoudeau

Reputation: 137

Possible to get the size of an Elasticsearch index through Java API?

I have been trying to get the size of my Elasticsearch index through the Java API, and I have not been able to find the right call to accomplish this. I found some suggestions like this one (https://groups.google.com/forum/#!topic/elasticsearch/jNCjCqAS1us), but it is from 2012 and seems to no longer be relevant.

I have been able to get an IndicesStatsResponse the following way:

IndicesStatsResponse response = client.admin().indices()
        .prepareStats(makeIndexName(tenant.getId()))
        .clear()
        .setStore(true)
        .execute()
        .actionGet();

but from this point I cannot find the information that I need. Is this possible?

Upvotes: 4

Views: 3621

Answers (3)

zella
zella

Reputation: 4685

With RestHighLevelClient, tested with es 7.1.0:

RestHighLevelClient client = ...;

var resp = client.getLowLevelClient().performRequest(new Request("GET", "INDEX_NAME/_stats"));
var body =  new ObjectMapper().readTree(resp.getEntity().getContent());
var size = body.get("indices").get("INDEX_NAME").get("primaries").get("store").get("size_in_bytes");

I use Jackson to parse json.

Upvotes: 3

pra
pra

Reputation: 1

IndicesStatsResponse response =client.admin().indices().prepareStats(indexName).clear().setStore(true).execute().actionGet();
ByteSizeValue bsv = response.getIndex(indexName).getTotal().getStore().getSize();

Upvotes: 0

Animesh Pandey
Animesh Pandey

Reputation: 6018

The index stats can be accessed using the Stats API.

  • Using cURL: curl -XGET localhost:9200/index_name/_stats?pretty=true where under store you have size_in_bytes

  • Using the Java API: IndexStatsResponse is a response that has to be converted to a JSON if you want to read it. You can use gson to parse te Json.

        IndicesStatsResponse indicesStatsResponse = StartTCPService.getClient()
                .admin()
                .indices()
                .prepareStats(index_name)
                .all()
                .execute().actionGet();
    
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        indicesStatsResponse.toXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        String jsonResponse = builder.prettyPrint().string();
    
        JsonParser jsonParser = new JsonParser(); // from import com.google.gson.JsonParser;
        Long sizeOfIndex = jsonParser.parse(jsonResponse)
                .getAsJsonObject().get("_all")
                .getAsJsonObject().get("primaries")
                .getAsJsonObject().get("store")
                .getAsJsonObject().get("size_in_bytes").getAsLong();
    
        System.out.println(sizeOfIndex); // this is in Bytes
    

Upvotes: 3

Related Questions