ElasticSearch index exists not working / reliable

The skgemini's answer is ok if you want to check if index is available by the actual index name or any of its aliases.

If you however want to check only by the index name, here is how.

public boolean checkIfIndexExists(String index) {

    IndexMetaData indexMetaData = client.admin().cluster()
            .state(Requests.clusterStateRequest())
            .actionGet()
            .getState()
            .getMetaData()
            .index(index);

    return (indexMetaData != null);

}

You can also execute a synchronous request like this:

boolean exists = client.admin().indices()
    .prepareExists(INDEX_NAME)
    .execute().actionGet().isExists();

Here is my solution when using RestHighLevelClient client;

Here a code-snippet: :

public boolean checkIfIndexExists(String indexName) throws IOException {
            Response response = client.getLowLevelClient().performRequest("HEAD", "/" + indexName);
            int statusCode = response.getStatusLine().getStatusCode(); 
            return (statusCode != 404);
    }

A contribution for someone else !


OK, I figured out a solution. Since the java client's calls are done asynchronously you have to use the variant which takes an action listener. The solution still gets a bit contrived though:

// Inner class because it's just used to be thrown out of
// the action listener implementation to signal that the
// index exists
private class ExistsException extends RuntimeException {
}

public boolean exists() {
    logger.info(String.format("Verifying existence of index \"%s\"", indexName));
    IndicesExistsRequest request = new IndicesExistsRequest(indexName);
    try {
        adminClient.exists(request, new ActionListener<IndicesExistsResponse>() {
            public void onResponse(IndicesExistsResponse response) {
                if (response.isExists()) {
                    throw new ExistsException();
                }
            }
            public void onFailure(Throwable e) {
                ExceptionUtil.smash(e);
            }
        });
    }
    catch (ExistsException e) {
        return true;
    }
    return false;
}