一尘不染

如何使用Elastic的High Level Rest Client获取所有索引?

elasticsearch

我想要一个很好的,快速且容易的方法,使用它们的Java
REST客户端
在elasticsearch中获取所有索引。我目前能够通过抓住他们的较低级别的客户端来做到这一点,如下所示:

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;
    }
}

本质上,我只是按照其文档中的建议将其称为/_cat/indices?v端点。这可以正常工作,但是我想知道是否有使用Java
API的更好的方法。我似乎无法在他们当前的API中找到方法,但想知道是否有人知道我不知道的东西。必须使用s和各个s并不一定很糟糕,而只是想清理hacky字符串解析。InputStream``Reader


阅读 1875

收藏
2020-06-22

共1个答案

一尘不染

从Elasticsearch 7.5.0开始,您可以使用以下方法检索所有索引:

    GetIndexRequest request = new GetIndexRequest("*");
    GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
    String[] indices = response.getIndices();
2020-06-22