【问题标题】:Painless scripting initialize new array无痛脚本初始化新数组
【发布时间】:2020-09-24 10:00:56
【问题描述】:

我正在尝试使用脚本在 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": []
        }
      }
    }
  }
}

【问题讨论】:

    标签: elasticsearch-painless


    【解决方案1】:

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

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

    在 JS 示例中是否有这样的简写?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      相关资源
      最近更新 更多