ElasticSearch索引存在不可行/可靠

use*_*845 12 java elasticsearch

我正在围绕ElasticSearch的管理客户端编写一个简单的Java包装器.为了测试它,我有一个main方法,首先检查索引是否存在(IndicesExistsRequest),如果是,则删除它(DeleteIndexRequest),并再次创建索引.见下面的代码.然而,我一直得到IndexAlreadyExistsException.

顺便说一句,我试图从命令提示符(通过简单地键入"弹性搜索")获取节点的客户端.我在nodeBuilder的流畅界面上尝试了各种方法组合,但我似乎无法得到一个.

public static void main(String[] args) {
    ElasticSearchJavaClient esjc = new ElasticSearchJavaClient("nda");
    if (esjc.indexExists()) {
        esjc.deleteIndex();
    }
    esjc.createIndex();
    URL url = SchemaCreator.class.getResource("/elasticsearch/specimen.type.json");
    String mappings = FileUtil.getContents(url);
    esjc.createType("specimen", mappings);
}

final Client esClient;
final IndicesAdminClient adminClient;
final String indexName;

public ElasticSearchJavaClient(String indexName) {
    this.indexName = indexName;
    esClient = nodeBuilder().clusterName("elasticsearch").client(true).node().client();
    adminClient = esClient.admin().indices();
}

public boolean deleteIndex() {
    logger.info("Deleting index " + indexName);
    DeleteIndexRequest request = new DeleteIndexRequest(indexName);
    try {
        DeleteIndexResponse response = adminClient.delete(request).actionGet();
        if (!response.isAcknowledged()) {
            throw new Exception("Failed to delete index " + indexName);
        }
        logger.info("Index deleted");
        return true;
    } catch (IndexMissingException e) {
        logger.info("No such index: " + indexName);
        return false;
    }
}

public boolean indexExists() {
    logger.info(String.format("Verifying existence of index \"%s\"", indexName));
    IndicesExistsRequest request = new IndicesExistsRequest(indexName);
    IndicesExistsResponse response = adminClient.exists(request).actionGet();
    if (response.isExists()) {
        logger.info("Index exists");
        return true;
    }
    logger.info("No such index");
    return false;
}

public void createIndex() {
    logger.info("Creating index " + indexName);
    CreateIndexRequest request = new CreateIndexRequest(indexName);
    IndicesAdminClient iac = esClient.admin().indices();
    CreateIndexResponse response = iac.create(request).actionGet();
    if (!response.isAcknowledged()) {
        throw new Exception("Failed to delete index " + indexName);
    }
    logger.info("Index created");
}
Run Code Online (Sandbox Code Playgroud)

小智 26

您还可以执行如下的同步请求:

boolean exists = client.admin().indices()
    .prepareExists(INDEX_NAME)
    .execute().actionGet().isExists();
Run Code Online (Sandbox Code Playgroud)


npe*_*npe 5

如果您想通过实际索引名称或其任何别名检查索引是否可用,skgemini 的答案是可以的。

但是,如果您只想通过索引名称进行检查,请按以下方法操作。

public boolean checkIfIndexExists(String index) {

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

    return (indexMetaData != null);

}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我使用 RestHighLevelClient 客户端时的解决方案;

这是一个代码片段::

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

对别人的贡献!


use*_*845 3

好吧,我想出了一个解决方案。由于 java 客户端的调用是异步完成的,因此您必须使用采用操作侦听器的变体。不过,解决方案仍然有点做作:

// 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;
}
Run Code Online (Sandbox Code Playgroud)