最近产品提了个新需求,需要按照查询筛选结果,支持批量删除es数据,es的版本号是5.6.x
下面内容是根据前端传参ids进行的批量删除
@RequestMapping(value = "/delete ", method = RequestMethod.DELETE)
public Object delete (@RequestBody List<String> ids){
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
int deleted= 0;
if(ids !=null){
BoolQueryBuilder subQuery = QueryBuilders.boolQuery();
for(int i = 0; i< ids.size(); i++){
subQuery.should(QueryBuilders.termQuery("_id",ids.get(i)));
}
queryBuilder.must(subQuery);
BulkByScrollResponse response =
DeleteByQueryAction.INSTANCE.newRequestBuilder(esClient.getESClient())
.filter(queryBuilder)
.source("这填索引名称").refresh(true)// refresh true是因为es删除有延迟,此处立即刷新就是为了从页面上 ,删除后立马就看不见数据
.get();
deleted = (int) response.getDeleted();//返回具体删除的条数
}
return deleted;
}
@Component
public class EsClient{
@ApiObjectField(description = "esName")
@Value("${es.name}")
private String esName;
@ApiObjectField(description = "esAddress")
@Value("${es.address}")
private String esAddress;
@ApiObjectField(description = "esPort")
@Value("${es.port}")
private Integer port;
private static TransportClient client = null;
/**
* 获取ESClient,如果Client为空则调用refreshClient来生成。
* @return
*/
@PostConstruct
public TransportClient getESClient(){
if(null == client){
try {
refreshClient(esName, esAddress, port);
} catch (UnknownHostException unknownEx) {
}
}
return client;
}
/**
* 静态方法,类加载时调用此方法
* @param clusterName
* @param hosts
* @param esPort
* @throws RuntimeException
*/
public void refreshClient(String clusterName, String hosts,int esPort) throws RuntimeException, UnknownHostException{
hosts = hosts.trim();
clusterName = clusterName.trim();
if(StringUtils.isEmpty(clusterName)){
throw new RuntimeException("Elastic Search Cluster Name is empty.");
}
if(StringUtils.isEmpty(hosts)){
throw new RuntimeException("Elastic Search Hosts is empty.");
}
Settings settings = Settings.builder().put("client.transport.sniff", false)
.put("cluster.name", clusterName).build();
client = new PreBuiltTransportClient(settings);
if(hosts.endsWith(";")){
hosts = hosts.substring(0, hosts.length() - 1);
}
String[] hostsArray = hosts.split(";");
for(String host : hostsArray){
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), esPort));
}
}
}
完成啦~