弹性搜索索引存在不起作用/不可靠

2022-09-03 17:00:53

我正在围绕ElasticSearch的管理客户端编写一个简单的Java包装器。为了测试它,我有一个主要方法,首先检查索引是否存在(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 create index " + indexName);
    }
    logger.info("Index created");
}

答案 1

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

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

答案 2

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

这里有一个代码片段: :

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

为别人做贡献!


推荐