【问题标题】:How to upsert nested objects with dynamic properties in Elastic Search?如何在 Elastic Search 中插入具有动态属性的嵌套对象?
【发布时间】:2020-02-06 17:26:37
【问题描述】:

我在 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 请求来更新/增加现有属性值非常有用!但是,如果我尝试在 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 方法,但是,发生了同样的错误:

脚本Upsert

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

谁能告诉我如何在postCategories 对象下正确添加/更新新属性名称?

谢谢!

【问题讨论】:

    标签: elasticsearch kibana elasticsearch-query


    【解决方案1】:

    它基本上是说您正在尝试为不存在的字段分配值。我认为下面应该可以工作(未经测试)。

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 2018-11-14
      相关资源
      最近更新 更多