如何在 Elastic Search 中插入具有动态属性的嵌套对象?

How to upsert nested objects with dynamic properties in Elastic Search?

我在 elasticsearch 中有一个如下所示的文档:

{
    "_index": "stats",
    "_type": "_doc",
    "_id": "1",
    "_score": 1.0,
    "_source": {
        "publishTime": {
            "lastUpdate": 1580991095131,
            "h0_4": 0,
            "h4_8": 0,
            "h8_12": 3,
            "h12_16": 5,
            "h16_20": 2,
            "h20_24": 1
        },
        "postCategories": {
             "lastUpdate": 1580991095131,
             "tech": 56,
             "lifestyle": 63,
             "healthcare": 49,
             "finances": 25,
         }
     }
 }
通过向 /stats/_update/1 发送 POST 请求,

Updating/Incrementing 现有 属性 值效果很好!但是,如果我尝试在 postCategories 下插入一个不存在的 属性 名称,我会收到类型为 remote_transport_exception/illegal_argument_exception:

Bad Request (400) 错误
"ctx._source.postCategories.relationships += params.postCategories.relationships",
                                                                  ^---- HERE"

更新

{
    "script": {
        "source": "ctx._source.postCategories.relationships += params.postCategories.relationships",
        "lang": "painless",
        "params": {
            "postCategories": {
                "relationships": 2
            }
        }
    },
    "upsert": {
       "postCategories": {
            "relationships": 2
        }
    }
}

我也按照here中的文档尝试了Scripted Upsert方法,但是,出现了同样的错误:

脚本更新插入

{
    "scripted_upsert":true,
    "script": {
        "source": "ctx._source.postCategories.relationships += params.postCategories.relationships",
        "params": {
            "postCategories": {
                "relationships": 2
            }
        }
    },
    "upsert": {}
}

谁能告诉我如何在 postCategories 对象下正确 add/upsert 新的 属性 名称?

谢谢!

这基本上是在说您正在尝试为一个不存在的字段赋值。我认为下面应该工作(未测试)。

尝试检查字段是否存在 - 如果存在则继续操作。 否则添加新字段并分配值。

"if (ctx._source.postCategories.containsKey(\"relationships\")) { ctx._source.postCategories.relationships += params.postCategories.relationships} else { ctx._source.postCategories[\"relationships\"] = params.postCategories.relationships}",