教程 elasticsearch tutorial

Scripted Fields

Scripted Fields(脚本字段)允许用户在查询时动态计算字段值,而无需预先索引这些字段,增强了数据的灵活性和查询能力。

1. Scripted Fields 概述

  • 利用 Painless 脚本动态生成字段
  • 可用于排序、过滤和聚合
  • 不修改原始数据,仅在查询时计算

2. 示例:基于两个字段计算新字段

json
GET /my-index/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "discounted_price": {
      "script": {
        "source": "doc['price'].value * 0.9",
        "lang": "painless"
      }
    }
  }
}

`

3. 结合 Scripted Fields 排序

json
GET /my-index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "source": "doc['price'].value * doc['popularity'].value",
        "lang": "painless"
      },
      "order": "desc"
    }
  }
}

4. 注意事项

  • 脚本字段计算在查询时执行,可能影响性能
  • 尽量避免复杂计算,推荐缓存常用脚本
  • 确保字段存在并可用,避免运行时错误

使用 Scripted Fields,可以实现更灵活的查询和排序需求,提升 Elasticsearch 的应用深度。