elasticsearch中bucket_script聚合父级必须是多桶聚合

本文详细分析了在Elasticsearch中使用反内联(reverse_nested)聚合与桶脚本(bucket_script)聚合时出现的错误,并提供了解决方案。通过调整聚合层级,将bucket_script聚合与reverse_nested聚合放在同一层级并正确设置关联路径,成功解决了计算人均通话数时遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景

业务需求中,在计算人均通话数时,使用聚合的时候使用到了内联以及反内联聚合,当bucket_script聚合作为反内联reverse_nested的子聚和的时候,会报如下错误:

org.elasticsearch.ElasticsearchException: Elasticsearch exception [type=class_cast_exception, reason=org.elasticsearch.search.aggregations.bucket.nested.InternalReverseNested cannot be cast to org.elasticsearch.search.aggregations.InternalMultiBucketAggregation]

该场景中的嵌套聚合中的子聚合如下(父级聚合此处不展示):

{
	"reverse_nested": {
		"reverse_nested": {},
		"aggregations": {
			"agg_count": {
				"value_count": {
					"field": "taskId.keyword"
				}
			},
			"agg_cardinality_tel": {
				"cardinality": {
					"field": "tel.keyword"
				}
			},
			"agg_bucketScript": {
				"bucket_script": {
					"buckets_path": {
						"userCount": "agg_cardinality_tel",
						"docCount": "agg_count"
					},
					"script": {
						"source": "params.docCount / params.userCount",
						"lang": "painless"
					},
					"gap_policy": "skip"
				}
			}
		}
	}
}

原因分析

bucket_script聚合的是建立在多桶聚合的前提下,即父级聚合必须是多桶聚合,官方文档已对此做过说明。

bucket_selector 等聚合方式的聚合场景亦是如此。

A parent pipeline aggregation which executes a script which can perform per bucket computations on specified metrics in the parent multi-bucket aggregation. The specified metric must be numeric and the script must return a numeric value.

解决方案

bucket_script聚合与reverse_nested聚合放在同层级,关联path即可。

{
	"reverse_nested": {
		"reverse_nested": {},
		"aggregations": {
			"agg_count": {
				"value_count": {
					"field": "taskId.keyword"
				}
			},
			"agg_cardinality_tel": {
				"cardinality": {
					"field": "tel.keyword"
				}
			}
		}
	},
	"agg_bucketScript": {
		"bucket_script": {
			"buckets_path": {
				"userCount": "reverse_nested>agg_cardinality_tel",
				"docCount": "reverse_nested>agg_count"
			},
			"script": {
				"source": "params.docCount / params.userCount",
				"lang": "painless"
			},
			"gap_policy": "skip"
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值