在_update_by_query期间插入缺少的文档

问题描述 投票:0回答:1

我有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一样运行:INSERT ... ON DUPLICATE KEY UPDATE

elasticsearch insert-update
1个回答
1
投票

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

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

POST testindex/_doc/iphone/_update
{
    "script" : {
        "source": "ctx._source.weight++",
        "lang": "painless"
    },
    "upsert" : {
        "weight" : 1
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.