Api
@Slf4j @Component public class DeleteApi { @Autowired private RestHighLevelClient client; @Autowired @Qualifier("deleteListener") private ActionListener listener; public void delete(String index, String id){ DeleteRequest request = new DeleteRequest(index, id); // request.routing("routing"); // request.timeout(TimeValue.timeValueMinutes(2)); //// request.timeout("2m"); // request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); //// request.setRefreshPolicy("wait_for"); // request.version(2); // request.versionType(VersionType.EXTERNAL); try { DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT); if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) { //如果要删除的文档没有找到,执行什么操作 log.info("delete index:" + index + ",id: " + id + "faild"); return; } client.deleteAsync(request, RequestOptions.DEFAULT, listener); }catch (IOException e){ e.printStackTrace(); }catch (ElasticsearchException exception) { if (exception.status() == RestStatus.CONFLICT) { //引发的异常表明返回了版本冲突错误 } } } }
Listener
@Configuration public class ESDeleteListener { @Bean("deleteListener") public ActionListener listener(){ ActionListener listener = new ActionListener<DeleteResponse>() { @Override public void onResponse(DeleteResponse deleteResponse) { String index = deleteResponse.getIndex(); String type = deleteResponse.getType(); String id = deleteResponse.getId(); long version = deleteResponse.getVersion(); ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo(); if (shardInfo.getTotal() != shardInfo.getSuccessful()) { //处理成功分片的数量少于总分片的情况 } if (shardInfo.getFailed() > 0) { for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) { //处理潜在的故障 String reason = failure.reason(); } } } @Override public void onFailure(Exception e) { } }; return listener; } }
请求示例