0

0

ElasticSearch 6.x 学习笔记:22.桶聚合

爱谁谁

爱谁谁

发布时间:2025-07-12 09:14:27

|

328人浏览过

|

来源于php中文网

原创

为了满足桶聚合多样性需求,修改文档如下。

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">DELETE my-indexPUT my-indexPUT my-index/persion/1{  "name":"张三",  "age":27,  "gender":"男",  "salary":15000,  "dep":"bigdata"}PUT my-index/persion/2{  "name":"李四",  "age":26,  "gender":"女",  "salary":15000,  "dep":"bigdata"}PUT my-index/persion/3{  "name":"王五",  "age":26,  "gender":"男",  "salary":17000,  "dep":"AI"}PUT my-index/persion/4{  "name":"刘六",  "age":27,  "gender":"女",  "salary":18000,  "dep":"AI"}PUT my-index/persion/5{  "name":"程裕强",  "age":31,  "gender":"男",  "salary":20000,  "dep":"bigdata"}PUT my-index/persion/6{  "name":"hadron",  "age":30,  "gender":"男",  "salary":20000,  "dep":"AI"}</code>
22.0 Bucket aggregations

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket.html 在页面右下角可以看到各类具体的Bucket聚合连接

ElasticSearch 6.x 学习笔记:22.桶聚合
22.1 Terms Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-terms-aggregation.html A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value. Terms聚合用于分组聚合。 【例子】根据薪资水平进行分组,统计每个薪资水平的人数

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "terms": {"field": "salary"}    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 7,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 6,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "doc_count_error_upper_bound": 0,      "sum_other_doc_count": 0,      "buckets": [        {          "key": 15000,          "doc_count": 2        },        {          "key": 20000,          "doc_count": 2        },        {          "key": 17000,          "doc_count": 1        },        {          "key": 18000,          "doc_count": 1        }      ]    }  }}</code>

【例子】统计上面每个分组的平均年龄

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "terms": {"field": "salary"},      "aggs":{        "avg_age":{          "avg":{"field": "age"}        }      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 4,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 6,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "doc_count_error_upper_bound": 0,      "sum_other_doc_count": 0,      "buckets": [        {          "key": 15000,          "doc_count": 2,          "avg_age": {            "value": 26.5 }        },        {          "key": 20000,          "doc_count": 2,          "avg_age": {            "value": 30.5 }        },        {          "key": 17000,          "doc_count": 1,          "avg_age": {            "value": 26 }        },        {          "key": 18000,          "doc_count": 1,          "avg_age": {            "value": 27 }        }      ]    }  }}</code>

【例子】统计每个部门的人数

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "terms": {"field": "dep"}    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "error": {    "root_cause": [      {        "type": "illegal_argument_exception",        "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [dep] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."      }    ],    "type": "search_phase_execution_exception",    "reason": "all shards failed",    "phase": "query",    "grouped": true,    "failed_shards": [      {        "shard": 0,        "index": "my-index",        "node": "cNWkQjt9SzKFNtyx8IIu-A",        "reason": {          "type": "illegal_argument_exception",          "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [dep] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."        }      }    ]  },  "status": 400}</code>

根据错误提示”Fielddata is disabled on text fields by default. Set fielddata=true on [dep] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.”可知,需要开启fielddata参数。只需要设置某个字段"fielddata": true即可。 此外,根据官方文档提示se the my_field.keyword field for aggregations, sorting, or in scripts,可以尝试my_field.keyword格式用于聚合操作。

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "terms": {"field": "dep.keyword"}    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 55,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 6,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "doc_count_error_upper_bound": 0,      "sum_other_doc_count": 0,      "buckets": [        {          "key": "AI",          "doc_count": 3        },        {          "key": "bigdata",          "doc_count": 3        }      ]    }  }}</code>
22.2 Filter Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-filter-aggregation.html Defines a multi bucket aggregation where each bucket is associated with a filter. Each bucket will collect all documents that match its associated filter. Filter聚合用于过滤器聚合,把满足过滤器条件的文档分到一组。

【例子】计算男人的平均年龄 也就是统计gender字段包含关键字“男”的文档的age平均值。

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "filter": {        "term":{"gender": "男"}      },      "aggs":{        "avg_age":{          "avg":{"field": "age"}        }      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 2,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 6,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "doc_count": 4,      "avg_age": {        "value": 28.5      }    }  }}</code>
22.3 Filters Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-filters-aggregation.html Defines a single bucket of all the documents in the current document set context that match a specified filter. Often this will be used to narrow down the current aggregation context to a specific set of documents.

【例子】统计body字段包含”error”和包含”warning”的文档数

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">PUT /logs/message/_bulk?refresh{ "index" : { "_id" : 1 } }{ "body" : "warning: page could not be rendered" }{ "index" : { "_id" : 2 } }{ "body" : "authentication error" }{ "index" : { "_id" : 3 } }{ "body" : "warning: connection timed out" }GET logs/_search{  "size": 0,  "aggs" : {    "messages" : {      "filters" : {        "filters" : {          "errors" :   { "match" : { "body" : "error"   }},          "warnings" : { "match" : { "body" : "warning" }}        }      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 54,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 3,    "max_score": 0,    "hits": []  },  "aggregations": {    "messages": {      "buckets": {        "errors": {          "doc_count": 1 },        "warnings": {          "doc_count": 2 }      }    }  }}</code>

【例子】统计男女员工的平均年龄

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "filters":{        "filters": [          {"match":{"gender": "男"}},          {"match":{"gender": "女"}}        ]      },      "aggs":{        "avg_age":{            "avg":{"field": "age"}        }      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 5,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 6,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "buckets": [        {          "doc_count": 4,          "avg_age": {            "value": 28.5 }        },        {          "doc_count": 2,          "avg_age": {            "value": 26.5 }        }      ]    }  }}</code>
22.4 Range Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-range-aggregation.html

A multi-bucket value source based aggregation that enables the user to define a set of ranges - each representing a bucket. During the aggregation process, the values extracted from each document will be checked against each bucket range and “bucket” the relevant/matching document. Note that this aggregation includes the from value and excludes the to value for each range.

from..to区间范围是[from,to),也就是说包含from点,不包含to点 【例子】查询薪资在[0,10000),[10000,20000),[2000,+无穷大)三个范围的员工数

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "group_count": {      "range": {        "field": "salary",        "ranges": [            {"to": 10000},            {"from": 10000,"to":20000},              {"from": 20000}        ]      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 101,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 6,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "buckets": [        {          "key": "*-10000.0",          "to": 10000,          "doc_count": 0        },        {          "key": "10000.0-20000.0",          "from": 10000,          "to": 20000,          "doc_count": 4        },        {          "key": "20000.0-*",          "from": 20000,          "doc_count": 2        }      ]    }  }}</code>

【例子】查询发布日期在2016-12-01之前、2016-12-01至2017-01-01、2017-01-01之后三个时间区间的文档数

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET website/_search{  "size": 0,   "aggs": {    "group_count": {      "range": {        "field": "postdate",        "format":"yyyy-MM-dd",        "ranges": [            {"to": "2016-12-01"},            {"from": "2016-12-01","to":"2017-01-01"},              {"from": "2017-01-01"}        ]      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 24,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 9,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "buckets": [        {          "key": "*-2016-12-01",          "to": 1480550400000,          "to_as_string": "2016-12-01",          "doc_count": 0        },        {          "key": "2016-12-01-2017-01-01",          "from": 1480550400000,          "from_as_string": "2016-12-01",          "to": 1483228800000,          "to_as_string": "2017-01-01",          "doc_count": 7        },        {          "key": "2017-01-01-*",          "from": 1483228800000,          "from_as_string": "2017-01-01",          "doc_count": 2        }      ]    }  }}</code>
22.5 Date Range聚合

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-daterange-aggregation.html A range aggregation that is dedicated for date values. The main difference between this aggregation and the normal range aggregation is that the from and to values can be expressed in Date Math expressions, and it is also possible to specify a date format by which the from and to response fields will be returned. Note that this aggregation includes the from value and excludes the to value for each range. 专用于日期值的范围聚合。 这种聚合和正常范围聚合的主要区别在于,起始和结束值可以在日期数学表达式中表示,并且还可以指定返回起始和结束响应字段的日期格式。 请注意,此聚合包含from值并排除每个范围的值。

【例子】计算一年前之前发表的博文数和从一年前以来发表的博文总数

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET website/_search{  "size": 0,   "aggs": {    "group_count": {      "range": {        "field": "postdate",        "format":"yyyy-MM-dd",        "ranges": [            {"to": "now-12M/M"},            {"from": "now-12M/M"}        ]      }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 44,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 9,    "max_score": 0,    "hits": []  },  "aggregations": {    "group_count": {      "buckets": [        {          "key": "*-2017-01-01",          "to": 1483228800000,          "to_as_string": "2017-01-01",          "doc_count": 7        },        {          "key": "2017-01-01-*",          "from": 1483228800000,          "from_as_string": "2017-01-01",          "doc_count": 2        }      ]    }  }}</code>
22.6 Missing聚合

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-missing-aggregation.html

A field data based single bucket aggregation, that creates a bucket of all documents in the current document set context that are missing a field value (effectively, missing a field or having the configured NULL value set). This aggregator will often be used in conjunction with other field data bucket aggregators (such as ranges) to return information for all the documents that could not be placed in any of the other buckets due to missing field data values. 基于字段数据的单桶集合,创建当前文档集上下文中缺少字段值(实际上缺少字段或设置了配置的NULL值)的所有文档的桶。 此聚合器通常会与其他字段数据存储桶聚合器(如范围)一起使用,以返回由于缺少字段数据值而无法放置在其他存储桶中的所有文档的信息。

艺映AI
艺映AI

艺映AI - 免费AI视频创作工具

下载
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">PUT my-index/persion/7{  "name":"test",  "age":30,  "gender":"男"}PUT my-index/persion/8{  "name":"abc",  "age":28,  "gender":"女"}PUT my-index/persion/9{  "name":"xyz",  "age":32,  "gender":"男",  "salary":null,  "dep":null}</code>

salary字段缺少的文档

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">GET my-index/_search{  "size": 0,   "aggs": {    "noDep_count": {      "missing": {"field": "salary"}    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 29,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 9,    "max_score": 0,    "hits": []  },  "aggregations": {    "noDep_count": {      "doc_count": 3    }  }}</code>
22.7 children聚合

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-children-aggregation.html

A special single bucket aggregation that selects child documents that have the specified type, as defined in a join field. 一个特殊的单桶集合,用于选择具有指定类型的子文档,如join字段中定义的。

这种聚合有一个单一的选择:type - 应该选择的子类型.

【例子】 (1)索引定义 下面通过join字段定义了一个单一关系,question 是answer的父文档。

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">PUT join_index{  "mappings": {    "doc": {      "properties": {        "my_join_field": {           "type": "join",          "relations": {            "question": "answer"           }        }      }    }  }}</code>

(2)父文档question

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">PUT join_index/doc/1?refresh{  "text": "This is a question",  "my_join_field": {    "name": "question"   }}PUT join_index/doc/2?refresh{  "text": "This is a another question",  "my_join_field": {    "name": "question"  }}</code>

(3)子文档answer

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">PUT join_index/doc/3?routing=1&refresh {  "text": "This is an answer",  "my_join_field": {    "name": "answer",     "parent": "1"   }}PUT join_index/doc/4?routing=1&refresh{  "text": "This is another answer",  "my_join_field": {    "name": "answer",    "parent": "1"  }}</code>

(4)统计子文档数量

代码语言:javascript代码运行次数:0运行复制
<code class="javascript">POST join_index/_search{  "size": 0,   "aggs": {    "to-answers": {        "children": {          "type" : "answer"         }    }  }}</code>
代码语言:javascript代码运行次数:0运行复制
<code class="javascript">{  "took": 4,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 4,    "max_score": 0,    "hits": []  },  "aggregations": {    "to-answers": {      "doc_count": 2    }  }}</code>
Global Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-global-aggregation.html

Defines a single bucket of all the documents within the search execution context. This context is defined by the indices and the document types you’re searching on, but is not influenced by the search query itself.

NOTE:Global aggregators can only be placed as top level aggregators because it doesn’t make sense to embed a global aggregator within another bucket aggregator.

Histogram Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-histogram-aggregation.html

IP Range Aggregation

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-iprange-aggregation.html

Just like the dedicated date range aggregation, there is also a dedicated range aggregation for IP typed fields:

Nested Aggregationedit

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-bucket-nested-aggregation.html

A special single bucket aggregation that enables aggregating nested documents.

For example, lets say we have an index of products, and each product holds the list of resellers - each having its own price for the product. The mapping could look like:

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
c语言中null和NULL的区别
c语言中null和NULL的区别

c语言中null和NULL的区别是:null是C语言中的一个宏定义,通常用来表示一个空指针,可以用于初始化指针变量,或者在条件语句中判断指针是否为空;NULL是C语言中的一个预定义常量,通常用来表示一个空值,用于表示一个空的指针、空的指针数组或者空的结构体指针。

253

2023.09.22

java中null的用法
java中null的用法

在Java中,null表示一个引用类型的变量不指向任何对象。可以将null赋值给任何引用类型的变量,包括类、接口、数组、字符串等。想了解更多null的相关内容,可以阅读本专题下面的文章。

1089

2024.03.01

typedef和define区别
typedef和define区别

typedef和define区别在类型检查、作用范围、可读性、错误处理和内存占用等。本专题为大家提供typedef和define相关的文章、下载、课程内容,供大家免费下载体验。

119

2023.09.26

define的用法
define的用法

define用法:1、定义常量;2、定义函数宏:3、定义条件编译;4、定义多行宏。更多关于define的用法的内容,大家可以阅读本专题下的文章。

384

2023.10.11

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

887

2023.07.31

python中的format是什么意思
python中的format是什么意思

python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

459

2024.06.27

scripterror怎么解决
scripterror怎么解决

scripterror的解决办法有检查语法、文件路径、检查网络连接、浏览器兼容性、使用try-catch语句、使用开发者工具进行调试、更新浏览器和JavaScript库或寻求专业帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

492

2023.10.18

500error怎么解决
500error怎么解决

500error的解决办法有检查服务器日志、检查代码、检查服务器配置、更新软件版本、重新启动服务、调试代码和寻求帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

377

2023.10.25

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

24

2026.03.09

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
CSS3 教程
CSS3 教程

共18课时 | 6.9万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 11.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号