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

Elastic Search聚合查询中如何为桶内top_hits结果添加脚本字段

操作方法

你编写好的distance计算脚本需要放置在top_hits聚合的参数体内,通过script_fields配置项加载即可生效,修改后的完整查询语句参考如下:

{
	"aggregations": {
		"groupByChains": {
			"terms": {
				"field": "chain.id",
				"size": 100,
				"min_doc_count": 1,
				"shard_min_doc_count": 0,
				"show_term_doc_count_error": false,
				"order": [
					{
						"_count": "desc"
					},
					{
						"_key": "asc"
					}
				]
			},
			"aggregations": {
				"topHits": {
					"top_hits": {
						"from": 0,
						"size": 100,
						"version": false,
						"seq_no_primary_term": false,
						"explain": false,
						"script_fields": {
							"distance": {
								"script": {
									"lang": "painless",
									"source": "替换为你已编写完成的distance计算脚本内容"
								}
							}
						}
					}
				}
			}
		}
	}
}

补充说明:新增的distance字段会默认和原文档的其他字段一同返回,如果你不需要返回原文档字段,仅保留计算后的distance,可以在top_hits参数中新增"_source": false配置。

内容的提问来源于stack exchange,提问作者shaik imran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:36:05