GrahamG21 GrahamG21 - 5 months ago 40
Java Question

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?

Answer

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