gpt4 book ai didi

java - ElasticSearch 索引存在不工作/不可靠

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:58 24 4
gpt4 key购买 nike

我正在围绕 ElasticSearch 的管理客户端编写一个简单的 Java 包装器。为了测试它,我有一个主要方法,首先检查索引是否存在 (IndicesExistsRequest),如果存在则删除它 (DeleteIndexRequest),然后再次创建索引。请参阅下面的代码。然而,我始终收到 IndexAlreadyExistsException。

顺便说一下,我正在尝试为您从命令提示符启动的节点获取客户端(只需键入“elastic search”)。我已经尝试了 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");
}

最佳答案

您也可以像这样执行同步请求:

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

关于java - ElasticSearch 索引存在不工作/不可靠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23883110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com