heez :
I want a nice, quick and easy way to get all of the indices in elasticsearch using the their Java REST client. I am currently able to do this by grabbing their lower level client, like this:
public void fetchIndices() throws IOException {
List<String> indices = null;
RestClient restClient = client.getLowLevelClient();
Response response = null;
try {
response = restClient.performRequest("GET", "/_cat/indices?v");
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString(), e);
}
InputStream inputStream = null;
if (response != null) {
try {
inputStream = response.getEntity().getContent();
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString(), e);
}
}
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
indices = new ArrayList<>();
String line;
while ((line = bufferedReader.readLine()) != null) {
// Get tokens with no whitespace
String[] tokens = line.split("\\s+");
for (String token : tokens) {
// TODO - make the startsWith() token configurable
if (token.startsWith(SOME_TOKEN)) {
LOGGER.log(Level.INFO, "Found elasticsearch index " + token);
indices.add(token);
break;
}
}
}
}
// Only update if we got data back from our REST call
if (indices != null) {
this.indices = indices;
}
}
Essentially I just call the /_cat/indices?v
endpoint as recommended in their docs. This works fine, but I was wondering if there was a nicer way to do this using the Java API. I can't seem to find a way in their current API, but wondering if anyone knows something I don't. Having to work with InputStream
s and the various Reader
s isn't necessarily terrible, but just want to clean up the hacky string parsing.
Mark Krijgsman :
As of Elasticsearch 7.5.0 you can use the following to retrieve all indices:
GetIndexRequest request = new GetIndexRequest("*");
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
String[] indices = response.getIndices();