无痛脚本编写新数组

时间:2020-09-24 10:00:56

标签: elasticsearch-painless

我正在尝试使用脚本在Elasticsearch中添加或更新嵌套对象。如果integrations已经是数组,则下面的脚本可以正常工作,但是当它为空时,下面的脚本将引发空指针异常。如果ctx._source.integrations的值为null,如何将其初始化为空数组? (有点像JavaScript的myObject.integrations = myObject.integrations ?? []

POST /products/_update/VFfrnQrKlC5bwdfdeaQ7
{
  "script": {
    "source": """
      ctx._source.integrations.removeIf(i -> i.id == params.integration.id);
      ctx._source.integrations.add(params.integration);

      ctx._source.integrationCount = ctx._source.integrations.length;
    """,
    "params": {
      "integration": {
        "id": "dVTV8GjHj8pXFnlYUUlI",
        "from": true,
        "to": false,
        "vendor": "sfeZWDpZXlF5Qa8mUsiF",
        "targetProduct": {
          "id": "nyILhphvCrGYm53cfaOx",
          "name": "Test Product",
          "categoryIds": []
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

好的,我认为这可以解决问题:

if (ctx._source.integrations == null) {
  ctx._source.integrations = new ArrayList();
}

在JS示例中是否有捷径?