You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch索引data1提取@authority字段最后值的脚本需求

Elasticsearch 提取@authority数组最后一个元素生成新字段

方案1:查询时动态生成脚本字段(临时需求)

如果不需要永久存储新字段,仅在查询时返回结果,可使用script_fields实现:

GET /data1/_search
{
  "script_fields": {
    "last_@authority": {
      "script": {
        "source": "def auth = doc['@authority']; return auth.length > 0 ? auth[auth.length - 1] : null;"
      }
    }
  }
}
  • 逻辑说明:doc['@authority']会自动将单值/多值字段转为数组,判断数组长度后取最后一个元素;若字段为空则返回null。

方案2:永久更新索引添加字段(长期需求)

如果需要将新字段永久写入索引,使用_update_by_query批量更新:

POST /data1/_update_by_query
{
  "script": {
    "source": "def auth = ctx._source['@authority']; if (auth != null) { ctx._source['last_@authority'] = auth instanceof List ? auth[auth.size() - 1] : auth; }",
    "lang": "painless"
  }
}
  • 逻辑说明:
    1. 先获取原字段@authority的值
    2. 判断字段是否为数组(List类型):是则取最后一个元素,否则直接赋值单值
    3. 增加null判断避免空字段报错

注意事项

  • 确保@authority字段在索引映射中允许多值存储(默认情况下,字符串字段若传入数组会自动处理为多值)
  • 若字段包含text类型,建议使用doc['@authority.keyword']来获取精确值(避免分词干扰)

内容的提问来源于stack exchange,提问作者Bibhudutta Mohanty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:37:42