桶选择器聚合
编辑桶选择器聚合
编辑一种父级管道聚合,它执行一个脚本,该脚本确定当前桶是否将保留在父级多桶聚合中。指定的指标必须是数值,并且脚本必须返回布尔值。如果脚本语言是 expression
,则允许返回数值。在这种情况下,0.0 将被评估为 false
,所有其他值将被评估为 true。
像所有管道聚合一样,bucket_selector 聚合在所有其他同级聚合之后执行。这意味着使用 bucket_selector 聚合来过滤响应中返回的桶并不会节省运行聚合的执行时间。
语法
编辑一个 bucket_selector
聚合单独看起来像这样
{ "bucket_selector": { "buckets_path": { "my_var1": "the_sum", "my_var2": "the_value_count" }, "script": "params.my_var1 > params.my_var2" } }
表 57. bucket_selector
参数
参数名 | 描述 | 必需 | 默认值 |
---|---|---|---|
|
此聚合要运行的脚本。脚本可以是内联的、文件或索引的。(有关更多详细信息,请参见脚本) |
必需 |
|
|
脚本变量及其关联的桶路径的映射,我们希望将这些桶用于变量(有关更多详细信息,请参见 |
必需 |
|
|
当数据中发现间隙时要应用的策略(有关更多详细信息,请参见处理数据中的间隙) |
可选 |
|
以下代码片段仅保留每月总销售额超过 200 的桶
resp = client.search( index="sales", size=0, aggs={ "sales_per_month": { "date_histogram": { "field": "date", "calendar_interval": "month" }, "aggs": { "total_sales": { "sum": { "field": "price" } }, "sales_bucket_filter": { "bucket_selector": { "buckets_path": { "totalSales": "total_sales" }, "script": "params.totalSales > 200" } } } } }, ) print(resp)
response = client.search( index: 'sales', body: { size: 0, aggregations: { sales_per_month: { date_histogram: { field: 'date', calendar_interval: 'month' }, aggregations: { total_sales: { sum: { field: 'price' } }, sales_bucket_filter: { bucket_selector: { buckets_path: { "totalSales": 'total_sales' }, script: 'params.totalSales > 200' } } } } } } ) puts response
const response = await client.search({ index: "sales", size: 0, aggs: { sales_per_month: { date_histogram: { field: "date", calendar_interval: "month", }, aggs: { total_sales: { sum: { field: "price", }, }, sales_bucket_filter: { bucket_selector: { buckets_path: { totalSales: "total_sales", }, script: "params.totalSales > 200", }, }, }, }, }, }); console.log(response);
POST /sales/_search { "size": 0, "aggs": { "sales_per_month": { "date_histogram": { "field": "date", "calendar_interval": "month" }, "aggs": { "total_sales": { "sum": { "field": "price" } }, "sales_bucket_filter": { "bucket_selector": { "buckets_path": { "totalSales": "total_sales" }, "script": "params.totalSales > 200" } } } } } }
以下可能是响应
{ "took": 11, "timed_out": false, "_shards": ..., "hits": ..., "aggregations": { "sales_per_month": { "buckets": [ { "key_as_string": "2015/01/01 00:00:00", "key": 1420070400000, "doc_count": 3, "total_sales": { "value": 550.0 } }, { "key_as_string": "2015/03/01 00:00:00", "key": 1425168000000, "doc_count": 2, "total_sales": { "value": 375.0 } } ] } } }