使用Java客户端创建一条文档记录,指定索引名为posts,类型为_doc,id为1就可以发起IndexRequest:
Map jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
IndexRequest indexRequest = new IndexRequest("posts", "_doc", "1")
.source(jsonMap);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
返回结果为IndexResponse,从中可以取得索引名称及ID,以及是否创建或更新操作:
String index = indexResponse.getIndex();
String id = indexResponse.getId();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
}
也可以进行异步创建文档,需要指定监听器对象来执行创建成功或失败时的操作。
ActionListener listener = new ActionListener() {
@Override
public void onResponse(IndexResponse indexResponse) {
}
@Override
public void onFailure(Exception e) {
}
};
client.indexAsync(request, RequestOptions.DEFAULT, listener);
异步创建不会等待创建完成才继续向下执行,所以如果创建过程很耗时,就可以使用这种异步的方式。
创建文档后,可以使用GET查询GetRequest。同样需要指定索引名称,索引类型,文档ID:
try {
GetRequest getRequest = new GetRequest(
"posts",
"_doc",
"1");
GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.CONFLICT) {
}
}
查询结果返回GetResponse,如果出现版本冲突就抛出异常。
删除操作使用DeleteRequest,返回对象为DeleteResponse:
DeleteRequest request = new DeleteRequest("posts”,”_doc","1");
DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);
查询文档是否存在,可以发送GetRequest,删除之后返回的结果为false。
GetRequest getRequest = new GetRequest(
"posts",
"_doc",
"1");
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
try {
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println("exists:" + exists);
} catch (IOException e) {
e.printStackTrace();
}
同样,更新操作使用UpdateRequest的doc方法,返回的对象UpdateResponse:
Map jsonMap = new HashMap<>();
jsonMap.put("updated", new Date());
jsonMap.put("reason", "daily update");
UpdateRequest request = new UpdateRequest("posts", “_doc", "1")
.doc(jsonMap);
UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);