在 _update_by_query 期间插入丢失的文档

Insert missing document during _update_by_query

我有一个包含 2 个字段的映射:消息 + 权重。
'Message' 每个文档都是唯一的。
每次检索文档时我都必须递增 'weight'。
如果找不到,我必须插入具有默认值的新文档。

有没有办法自动插入文档,如果没有找到,而 运行 _update_by_query?

POST /testindex/_update_by_query?conflicts=proceed
{
    "script": {
        "inline": "ctx._source.weight++",
        "lang": "painless"
    },
    "query": {
        "match": {
            "message": "iphone"
        }
    }
}

我需要它像 SQL 那样工作:插入…在重复密钥更新时

由于您的 message 字段对于所有文档都是唯一的,您可以将其用作文档 ID。这将使您能够利用 Update API,更具体地说,upsert 功能。

基本上,您可以更新文档(增加 weight),如果它不存在,则会创建它(使用 weight: 1):

POST testindex/_doc/iphone/_update
{
    "script" : {
        "source": "ctx._source.weight++",
        "lang": "painless"
    },
    "upsert" : {
        "weight" : 1
    }
}