es批量删除需要插件的支持
首先:在es上安装 delete-by-query插件
plugin install delete-by-query
重启es
service elasticsearch retsart
在我们的java项目中添加delete-by-query插件的依赖
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>delete-by-query</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
在我们的项目,es客户端连接的时候,加载插件
TransportClient client = TransportClient.builder()
.settings(settings)
.addPlugin(DeleteByQueryPlugin.class)
.build();
使用:
例子:根据fileId和accountId删除 file类型中对应的记录
/**
* 根据fileId和accountId删除 file类型中对应的记录
* @param accountId 账号id
* @param fileId 文件id
* @return 删除的行数
*/
public long batchDeleteFile(String accountId, String fileId) {
BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
boolQueryBuilder.must(QueryBuilders.termQuery("fileId",fileId));
if (accountId!=null){
boolQueryBuilder.must(QueryBuilders.termQuery("accountId",accountId));
}
DeleteByQueryResponse response = new DeleteByQueryRequestBuilder(client,
DeleteByQueryAction.INSTANCE)
.setIndices(INDEX_NAME)
.setTypes(FILE)
.setQuery(boolQueryBuilder)
.execute()
.actionGet();
return response.getTotalFound();
}