Get、Delete API————(获取、删除文档)
1.判断文档是否存在
private static boolean isExist(RestHighLevelClient client) throws IOException{
GetRequest request = new GetRequest("my_index", "my_type", "1");
boolean exists = client.exists(request, RequestOptions.DEFAULT);
ActionListener<Boolean> listener = new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean exists) {
if (exists){
System.out.println("文档存在");
}else {
System.out.println("文档不存在");
}
}
@Override
public void onFailure(Exception e) {
}
};
return exists;
}
2.获取文档
private static void getRequestData(RestHighLevelClient client) throws IOException {
GetRequest request = new GetRequest("my_index", "my_type", "1");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
ActionListener<GetResponse> listener = new ActionListener<GetResponse>() {
@Override
public void onResponse(GetResponse getResponse) {
System.out.println("获取成功");
}
@Override
public void onFailure(Exception e) {
System.out.println("获取失败");
}
};
Map<String, Object> source = response.getSource();
String sourceAsString = response.getSourceAsString();
Map<String, Object> sourceAsMap = response.getSourceAsMap();
byte[] sourceAsBytes = response.getSourceAsBytes();
BytesReference sourceInternal = response.getSourceInternal();
System.out.println(request);
System.out.println(response);
System.out.println(source);
System.out.println(sourceAsString);
System.out.println(sourceAsMap);
System.out.println(sourceAsBytes);
System.out.println(sourceInternal);
}
3.删除文档
private static void deleteDocument(RestHighLevelClient client) throws IOException{
DeleteRequest request = new DeleteRequest("my_index", "my_type", "6");
request.timeout(TimeValue.timeValueMinutes(2));
DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
ActionListener<DeleteResponse> listener = new ActionListener<DeleteResponse>() {
@Override
public void onResponse(DeleteResponse deleteResponse) {
System.out.println("删除后操作");
}
@Override
public void onFailure(Exception e) {
System.out.println("删除失败");
}
};
System.out.println(deleteResponse.toString());
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();
}
}
}