ES文档数据的新增、更新、删除、批量导入、分页查询、查询结果聚合功能
新增索引后默认的文档名称是_doc
1、新增文档数据
创建新增文档请求,设置数据内容,然后在设置一些可选参数,最后异步执行该请求
/**
* 新增单条文档数据
*
* @param indexName 索引名称
* @param id
* @throws Exception
*/
public void createDocument(String indexName, String id) throws Exception {
RestHighLevelClient client = this.getEsClient();
// 指定单条文档数据,最终会转化成Json格式
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("name", "张三");
builder.field("age", 12);
builder.field("email", "email123");
}
builder.endObject();
// 创建新增文档数据的请求
IndexRequest indexRequest = new IndexRequest(indexName).id(id).source(builder);
// 手动指定路由的key,文档查询时可提高性能
indexRequest.routing("userInfo");
// 等待主分片保存的超时时长
indexRequest.timeout(TimeValue.timeValueSeconds(1));
// 刷新策略,WAIT_UNTIL设置则表示刷新使此请求的内容对搜索可见为止
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
// 操作类型为新增
indexRequest.opType(DocWriteRequest.OpType.CREATE);
// 异步执行新增文档数据请求
client.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
System.out.println(indexResponse.toString());
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
}
});
}
2、更新文档数据
部分文档内容更新,Es采用乐观锁机制,每更新一次Version值加1
/**
* 更新文档内容
*
* @param indexName 索引名称
* @param id
*/
public void updateDocument(String indexName, String id) throws Exception {
RestHighLevelClient client = this.getEsClient();
// 更新部分文档内容
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("age", 25);
jsonMap.put("email", "email2020");
// 创建更新文档请求并设置参数
UpdateRequest updateRequest = n