部分更新Elasticsearch索引时的NPE

时间:2018-01-03 05:56:33

标签: elasticsearch aws-elasticsearch

我跟随here上的示例,使用Elasticsearch中的部分更新来更新一组标记。

以下是我的剧本:

{
  "script": {
    "lang": "painless",
    "inline": "ctx._source.deviceTags.add(params.tags)",
    "params": {
      "tags": "search"
    }
  }
}

请求网址为:

https://aws-es-service-url/devices/device/123/_update

但是我收到了以下回复:

{
    "error": {
        "root_cause": [
            {
                "type": "remote_transport_exception",
                "reason": "[fBaExM8][x.x.x.x:9300][indices:data/write/update[s]]"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "failed to execute script",
        "caused_by": {
            "type": "script_exception",
            "reason": "runtime error",
            "script_stack": [
                "ctx._source.deviceTags.add(params.tags)",
                "                                 ^---- HERE"
            ],
            "script": "ctx._source.deviceTags.add(params.tags)",
            "lang": "painless",
            "caused_by": {
                "type": "null_pointer_exception",
                "reason": null
            }
        }
    },
    "status": 400
}

知道我做错了什么?

1 个答案:

答案 0 :(得分:2)

由于您的deviceTags数组最初为null,因此您有两种方法可以解决此问题

一个。使用upsert确保deviceTags最初添加到您的文档

{
  "script": {
    "lang": "painless",
    "inline": "ctx._source.deviceTags.add(params.tags)",
    "params": {
      "tags": "search"
    }
  },
  "upsert": {
    "deviceTags": ["search"]
  }
}

B中。保护您的代码免受NPE

{
  "script": {
    "lang": "painless",
    "inline": "(ctx._source.deviceTags = ctx._source.deviceTags ?: []).add(params.tags)",
    "params": {
      "tags": "search"
    }
  }
}