背景
客戶為了實(shí)現(xiàn)search after功能,必須有一個(gè)modify_at字段在更新doc的時(shí)候不能修改,也就是更新的時(shí)候如果請(qǐng)求body里包含了這個(gè)modify_at字段,就不更新;但是同時(shí)又要保證upsert功能,在沒(méi)有該文檔的時(shí)候,就新增該文檔。
梳理一下,客戶的需求就是在upsert的同時(shí),實(shí)現(xiàn)部分更新。
實(shí)現(xiàn)方式
部分更新文檔的話就需要通過(guò)[update API] (https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html) 實(shí)現(xiàn),通過(guò)指定文檔id來(lái)實(shí)現(xiàn)部分更新,部分更新可以通過(guò)plainless script或者指定doc字段來(lái)實(shí)現(xiàn)
另外,update API 可以實(shí)現(xiàn)upsert功能,在body中指定upsert字段來(lái)實(shí)現(xiàn)。
綜上,最終通過(guò)如下方式解決了客戶的需求:
- 第一次寫(xiě)入,POST my_index/_update/1
通過(guò)script腳本實(shí)現(xiàn)部分更新,以及指定upsert功能在文檔1不存在時(shí)就插入:
{
"script": {
"source": "ctx._source.a = params.a;ctx._source.b = params.b;",
"lang": "painless",
"params": {
"a": 1,
"b": 1
}
},
"upsert": {
"a": 1,
"b": 1,
"modify_at": 1634819527790
}
}
或者通過(guò)指定doc字段實(shí)現(xiàn)部分更新:
{
"doc": {
"a": 1,
"b": 1
},
"upsert": {
"a": 1,
"b": 1,
"modify_at": 1634819527790
}
}
- 查看寫(xiě)入結(jié)果, GET my_index/_doc/1
{
"_index": "x",
"_id": "1",
"_version": 1,
"_seq_no": 12,
"_primary_term": 1,
"found": true,
"_source": {
"a": 1,
"b": 1,
"modify_at": 1634819527790
}
}
- 后續(xù)更新,方式和第一次寫(xiě)入相同,只不過(guò)傳值不同,客戶端對(duì)是要插入還是更新無(wú)感
{
"script": {
"source": "ctx._source.a = params.a;ctx._source.b = params.b;",
"lang": "painless",
"params": {
"a": 2,
"b": 2
}
},
"upsert": {
"a": 2,
"b": 2,
"modify_at": 1634819527790
}
}
或者
{
"doc": {
"a": 2,
"b": 2
},
"upsert": {
"a": 1,
"b": 1,
"modify_at": 1634819527790
}
}
- 獲取結(jié)果,GET my_index/_doc/1
{
"_index": "x",
"_id": "1",
"_version": 2,
"_seq_no": 13,
"_primary_term": 1,
"found": true,
"_source": {
"a": 2,
"b": 2,
"modify_at": 1634819527790
}
}