java - 如何删除 ElasticSearch 索引?

标签 java testing groovy elasticsearch

我的单元/集成测试包括搜索功能测试。

我的想法是在每次测试之前都有空的搜索索引。所以,我试图在 setup 方法(它是 Groovy 代码)上删除索引中的所有元素:

Client client = searchConnection.client

SearchResponse response = client.prepareSearch("item")
    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
    .setQuery(termQuery('name', 'test')) //tried also matchAllQuery()
    .setFrom(0).setSize(100).setExplain(false).execute().actionGet()

List<String> ids = response.hits.hits.collect {
    return it.id
}
client.close()

client = searchConnection.client

ids.each {
    DeleteResponse delete = client.prepareDelete("item", "item", it)
        .setOperationThreaded(false)
        .execute().actionGet()
}

client.close()

似乎它正在异步处理所有删除,所以我在它之后添加了 Thread.sleep(5000) 。如您所见,我试图打开/关闭连接几次 - 在那里没有帮助。

有时需要更多时间,有时需要超过 5 秒才能删除,有时无法找到刚刚添加的数据(来自以前的测试)等等。最烦人的是集成测试变得不稳定。将 Thread.sleep() 放在任何可能的地方看起来不是很好的解决方案。

有什么方法可以提交最后的更改,或锁定直到所有数据都被写入?

最佳答案

找到解决方案:

IndicesAdminClient adminClient = searchConnection.client.admin().indices();
String indexName = "location";
DeleteIndexResponse delete = adminClient.delete(new DeleteIndexRequest(indexName)).actionGet()
if (!delete.isAcknowledged()) {
    log.error("Index {} wasn't deleted", indexName);
}

client.admin().indices().flush(new FlushRequest('location')).actionGet();

将新数据放入索引后。

关于java - 如何删除 ElasticSearch 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8019221/

相关文章:

java - 如何创建页内配置。通过c :set?

java - Spring Boot - 大量无效请求和套接字接受失败 java.io.IOException : Too many open files

java - 如何为 REST 服务生成 WADL

shell - 如何让 Jenkins 2.0 在与结帐相同的目录中执行 sh 命令?

常规静态类

groovy - 传递 Map 和使用 `body.resolveStrategy = Closure.DELEGATE_FIRST` 有什么区别

java - 64 位 Java VM 运行应用程序速度慢 10 倍

java - 将 Eclipse 项目导出到 Runnable Jar 不起作用

iphone - iPhone 样机网络服务

testing - 所有节点的 Selenium -maxSession