Java Restapi Upsert 文档操作
文档更新
UpdateRequest request = new UpdateRequest(
"posts",
"doc",
"1");
String jsonString = "{" +
"\"updated\":\"2017-01-01\"," +
"\"reason\":\"daily update\"" +
"}";
request.doc(jsonString, XContentType.JSON);
doc 支持文档类型的 JSON, Map, XContentBuilder or Object key-pairs
文档局部脚本更新
Updates with a script
Map<String, Object> parameters = singletonMap("count", 4);
Script inline = new Script(ScriptType.INLINE, "painless",
"ctx._source.field += params.count", parameters);
request.script(inline);
Script stored = new Script(
ScriptType.STORED, null, "increment-field", parameters);
request.script(stored);
ScriptType.INLINE 和ScriptType.STORED区别未验证
文档更新或插入(upsert)
UpdateRequest request = new UpdateRequest(
"posts",
"doc",
"1");
String jsonString = "{" +
"\"updated\":\"2017-01-01\"," +
"\"reason\":\"daily update\"" +
"}";
//update数据源
request.doc(jsonString, XContentType.JSON);
//开户upsert
request.docAsUpsert(true);
//insert数据源
request.upsert(jsonString, XContentType.JSON);
upsert说明:
- 当设置 docAsUpsert(false)时,默认为false,更新请求检查发现文档不存在时(对应的ID文档),会抛出ElasticsearchException [document missing]
- 当设置 docAsUpsert(true)时,更新请求检查发现文档不存在时(对应的ID文档),会新增 request.doc 中设置的文档;
- 当设置 docAsUpsert(false)时,设置了upsert数据源时,当文档不存在时,会新增request.upsert内容设置的文档