赞
踩
在Elasticsearch中,如果您的文档结构包含嵌套对象(nested fields),直接对这些嵌套字段进行聚合可能会得到不准确的结果,因为Elasticsearch默认会扁平化处理嵌套对象。要正确地对嵌套字段进行聚合操作,您需要使用Elasticsearch提供的nested
聚合类型。以下是一个实战示例,说明如何对嵌套字段进行聚合:
假设您有一个名为orders
的索引,其中包含购买订单数据,每个订单文档结构如下:
{ "customer_id": "123", "order_date": "2022-0¼-01", "products": [ { "product_id": "P001", "quantity": 5, "price_per_unit": 10.99 }, { "product_id": "P002", "quantity": 3, "price_per_unit": 19.99 } ] }
在这个例子中,products
是一个嵌套类型的字段,因为它包含了多个具有相同结构的子对象。现在,您想按customer_id
分组,然后计算每个客户购买的每个产品的总销售额。
步骤如下:
定义嵌套类型:
在创建索引时,确保已将products
字段标记为nested
类型。例如:
PUT orders { "mappings": { "properties": { "customer_id": { "type": "keyword" }, "order_date": { "type": "date" }, "products": { "type": "nested", // 关键在这里 "properties": { "product_id": { "type": "keyword" }, "quantity": { "type": "long" }, "price_per_unit": { "type": "float" } } } } } }
执行嵌套聚合:
使用nested
聚合来处理嵌套字段,并在嵌套上下文中执行所需的度量聚合(如sum
):
GET orders/_search { "size": 0, // 只返回聚合结果 "aggs": { "customers": { "terms": { "field": "customer_id.keyword" }, "aggs": { "products": { "nested": { "path": "products" }, "aggs": { "sales_per_product": { "terms": { "field": "products.product_id.keyword" }, "aggs": { "total_sales": { "sum": { "field": "products.quantity", "script": { "source": "doc['products.price_per_unit'].value * doc['products.quantity'].value" } } } } } } } } } } }
在这个查询中:
customers
聚合使用terms
对customer_id
进行分组。products
聚合是一个nested
聚合,指定了嵌套路径为products
,这样Elasticsearch就会知道要对哪个嵌套字段进行操作。sales_per_product
聚合进一步按products.product_id
进行分组。total_sales
聚合使用sum
聚合器计算每个产品在每个订单中的销售额(即quantity
乘以price_per_unit
)。查询结果将展示每个客户的ID,以及他们购买的每个产品的总销售额。这就是对Elasticsearch中嵌套字段进行聚合操作的一个实战示例。根据实际业务需求,您可以调整聚合结构和参数,以实现更复杂的分析。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。