首页 > 解决方案 > 如何使用无痛脚本将新字段添加到文档中

问题描述

如果不存在,有没有办法在无痛脚本中创建文档中的字段?

我正在使用类似的东西:

     if(!ctx._source.tags.contains(....)

但文档中可能不存在标签字段

可以吗?

谢谢。

标签: elasticsearchelasticsearch-painless

解决方案


如果您打算使用_update_by_queryAPI,我建议您执行以下操作:

POST your_index/_update_by_query
{
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "tags"
        }
      }
    }
  },
  "script": {
    "source": "ctx._source.tags = ''"
  }
}

否则,只需使用无痛,您可以执行以下操作:

{
  "script": {
    "source": """
      if(ctx._source.tags == null) {
        ctx._source.tags = null;
      }
    """
  }
}

推荐阅读