Igo*_*nov 28 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()
Run Code Online (Sandbox Code Playgroud)
似乎它正在异步处理所有删除,所以我Thread.sleep(5000)在它之后添加了.如你所见,我试图打开/关闭连接几次 - 它没有帮助.
有时需要更多时间的问题,有时需要更多的时间来删除,有时它无法找到刚刚添加的数据(来自之前的测试)等等.最令人讨厌的是集成测试变得不稳定.把Thread.sleep()它放在任何可能的地方看起来都不是那么好的解决方案.
有没有办法提交最后的更改,或者锁定直到所有数据都被写入?
Igo*_*nov 34
找到解决方案
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);
}
Run Code Online (Sandbox Code Playgroud)
和
client.admin().indices().flush(new FlushRequest('location')).actionGet();
Run Code Online (Sandbox Code Playgroud)
将新数据放入索引后.
joh*_*hno 29
首先,您不必通过对每个文档ID发出删除来清除所有数据.您可以通过查询匹配所有文档删除所有数据删除所有文件http://www.elasticsearch.org/guide/reference/api/delete-by-query.html说完之后我也不建议这样做,因为它不是建议经常在大型文档集上执行此操作(请参阅docs).
你真正想做的是删除整个索引(它很快)http://www.elasticsearch.org/guide/reference/api/admin-indices-delete-index.html,重新创建它,输入数据,这是重要的是刷新索引以"提交"更改并使其可见.http://www.elasticsearch.org/guide/reference/api/admin-indices-refresh.html
我在测试中这样做,从来没有遇到过问题.
删除所有项目:
client.prepareDeleteByQuery(indexName).
setQuery(QueryBuilders.matchAllQuery()).
setTypes(indexType).
execute().actionGet();
Run Code Online (Sandbox Code Playgroud)刷新索引以查看更改(仅在单元测试中需要)
| 归档时间: |
|
| 查看次数: |
45613 次 |
| 最近记录: |