package org.fanli.elastic; import java.io.IOException; import org.apache.http.HttpHost; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.support.replication.ReplicationResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; public class DeleteUtils { private static String clusterName = "my-application"; private static String host = "192.168.1.200"; private static Integer port = 9200; // 相当于数据库名称 public static String indexName = "shose"; // 初始化api客户端 public static RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost(host, port, "http"))); public static void get1() { DeleteRequest request = new DeleteRequest("posts", "2"); // // 可选参数 // 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); // // // 返回的值DeleteResponse允许检索有关已执行操作的信息, // String index = deleteResponse.getIndex(); // 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(); // } // // 处理潜在的故障 // } // // // 可以检查是否找到了该文档: // DeleteRequest request = new DeleteRequest("posts", "does_not_exist"); // DeleteResponse deleteResponse = client.delete( // request, RequestOptions.DEFAULT); // if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) { // // } // // try { // DeleteResponse deleteResponse = client.delete( // new DeleteRequest("posts", "1").setIfSeqNo(100).setIfPrimaryTerm(2), // RequestOptions.DEFAULT); // } catch (ElasticsearchException exception) { // if (exception.status() == RestStatus.CONFLICT) { // // } // } // } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { get1(); System.out.println("------------ 测试结束 -------------------------"); } }