Supported APIs - Delete API

优质
小牛编辑
133浏览
2023-12-01

删除请求对象

DeleteRequest 需要下列参数:

  1. DeleteRequest request = new DeleteRequest(
  2. "posts", // index
  3. "doc", //Type
  4. "1"); // Document id

可选参数

提供下列可选参数:

  1. request.routing("routing"); // 路由值
  2. request.parent("parent"); //Parent 值
  3. request.timeout(TimeValue.timeValueMinutes(2)); // TimeValue 类型的等待主分片可用的超时时间
  4. request.timeout("2m"); // 字符串类型的等待主分片可用的超时时间
  5. request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); // Refresh policy as a WriteRequest.RefreshPolicy instance
  6. request.setRefreshPolicy("wait_for"); // Refresh policy as a String
  7. request.version(2); // Version
  8. request.versionType(VersionType.EXTERNAL); // Version type

同步执行

  1. DeleteResponse deleteResponse = client.delete(request);

异步执行

  1. client.deleteAsync(request, new ActionListener<DeleteResponse>() {
  2. @Override
  3. public void onResponse(DeleteResponse deleteResponse) {
  4. //Called when the execution is successfully completed. The response is provided as an argument
  5. }
  6. @Override
  7. public void onFailure(Exception e) {
  8. //Called in case of failure. The raised exception is provided as an argument
  9. }
  10. });

删除操作的响应

返回的 DeleteResponse 对象允许通过执行以下操作获取相关信息:

  1. String index = deleteResponse.getIndex();
  2. String type = deleteResponse.getType();
  3. String id = deleteResponse.getId();
  4. long version = deleteResponse.getVersion();
  5. ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
  6. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  7. // Handle the situation where number of successful shards is less than total shards
  8. }
  9. if (shardInfo.getFailed() > 0) {
  10. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
  11. String reason = failure.reason(); // Handle the potential failures
  12. }
  13. }

也可以检查文档是否被发现:

  1. DeleteRequest request = new DeleteRequest("posts", "doc", "does_not_exist");
  2. DeleteResponse deleteResponse = client.delete(request);
  3. if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
  4. //如果被删除的文档没有被找到,做某些操作
  5. }

如果有版本冲突,将抛出 ElasticsearchException 异常信息:

  1. try {
  2. DeleteRequest request = new DeleteRequest("posts", "doc", "1").version(2);
  3. DeleteResponse deleteResponse = client.delete(request);
  4. } catch (ElasticsearchException exception) {
  5. if (exception.status() == RestStatus.CONFLICT) {
  6. //由于版本冲突错误导致的异常
  7. }
  8. }