Java Elasticsearch:Document APIs
Eijux(讨论 | 贡献)2021年5月21日 (五) 22:31的版本 (建立内容为“category:ElasticSearch category:Java == Index Api == Java Elasticsearch Index API 主要用于插入或者更新文档数据。 === 创建Index Request…”的新页面)
Index Api
Java Elasticsearch Index API 主要用于插入或者更新文档数据。
创建Index Request
// 创建Index Request,设置索引名为: posts
IndexRequest request = new IndexRequest("posts");
// 设置文档ID
request.id("1");
设置文档内容
支持以JSON字符串形式或者Map形式设置文档内容。
JSON字符串形式:
// 创建 JSON字符串
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
// 设置文档内容
request.source(jsonString, XContentType.JSON);
Map形式:
// 创建 Map
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
// 设置文档内容
request.source(jsonMap);
可选参数
routing
设置路由字段
request.routing("routing");
timeout
设置单个请求超时参数
request.timeout(TimeValue.timeValueSeconds(1));
// or
request.timeout("1s");
Version
设置文档版本
request.version(2);
操作类型
Index api支持两类操作:create 或者 index (默认)
request.opType("create");
执行请求
同步执行
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
异步执行
IndexResponse indexResponse = client.indexAsync(request, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
// 请求成功回调函数
}
@Override
public void onFailure(Exception e) {
// 请求失败回调函数
}
});
处理请求结果
// 获取索引名
String index = indexResponse.getIndex();
// 获取文档ID
String id = indexResponse.getId();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
// 成功创建文档
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
// 成功更新文档
}
Get Api