注: 连接es以及依赖相关内容请自行配置,只提供方法。
依赖如下
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.8.0</version>
</dependency>
代码如下
@Autowired
private RestHighLevelClient elasticsearchClient;
public void deleteData() throws IOException {
// 构建查询请求
SearchRequest searchRequest = new SearchRequest("your_index_name"); // 替换为实际的索引名称
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("查询条件", "查询条件对应值"));
sourceBuilder.size(100); // 设置每次查询的文档数量
searchRequest.source(sourceBuilder);
// 执行查询请求
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
long totalHits = searchResponse.getHits().getTotalHits(); // 获取查询结果的总命中数
// 批量删除
int batchSize = 100; // 每批处理的文档数量
for (int i = 0; i < totalHits; i += batchSize) {
BulkRequest bulkRequest = new BulkRequest();
for (SearchHit hit : searchResponse.getHits().getHits()) {
String documentId = hit.getId();
DeleteRequest deleteRequest = new DeleteRequest("your_index_name", "your_index_name_type", documentId); // 替换为实际的索引名称和文档类型
bulkRequest.add(deleteRequest);
}
BulkResponse bulkResponse = elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
// 处理删除结果
if (bulkResponse.hasFailures()) {
System.out.println("Failed to delete documents");
} else {
System.out.println("Delete documents successfully");
}
// 获取下一批文档
if (i + batchSize < totalHits) {
sourceBuilder.from(i + batchSize); // 设置下一批查询的起始位置
searchRequest.source(sourceBuilder);
searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
}
}
文章来源地址https://www.toymoban.com/news/detail-810867.html
文章来源:https://www.toymoban.com/news/detail-810867.html
到了这里,关于java 操作elasticsearch 6.8.0 根据某个条件批量删除数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!