本章将介绍elasticsearch最重要的桶聚合terms aggregation。
Terms Aggregation
多值聚合,根据库中的文档动态构建桶。基于词根的聚合,如果聚合字段是text的话,会对一个一个的词根进行聚合,通常不会在text类型的字段上使用聚合,对标关系型数据中的(Group By)。
官方示例如下:
1GET /_search
2{
3 "aggs" : {
4 "genres" : {
5 "terms" : { "field" : "genre" }
6 }
7 }
8}
返回结果如下:
1{
2 ...
3 "aggregations" : {
4 "genres" : {
5 "doc_count_error_upper_bound": 0, // @1
6 "sum_other_doc_count": 0, // @2
7 "buckets" : [ // @3
8 {
9 "key" : "electronic",
10 "doc_count" : 6
11 },
12 {
13 "key" : "rock",
14 "doc_count" : 3
15 },
16 {
17 "key" : "jazz",
18 "doc_count" : 2
19 }
20 ]
21 }
22 }
23}
返回结果@1:该值表示未进入最终术语列表的术语的最大潜在文档计数,下文还会详细分析。
返回结果@2:当有很多词根时,Elasticsearch只返回最上面的项;这个数字是所有不属于响应的bucket的文档计数之和,其搜索过程在下文会讲到。
返回结果@3:返回的结果,默认情况下,返回doc_count排名最前的10个,受size参数的影响,下面会详细介绍。
Terms 聚合支持如下常用参数:
size
可以通过size返回top size的文档,该术语聚合针对顶层术语(不包含嵌套词根),其搜索过程是将请求向所有分片节点发送请求,每个分片节点返回size条数据,然后聚合所有分片的结果(会对各分片返回的同样词根的数数值进行相加),最终从中挑选size条记录返回给客户端。从这个过程也可以看出,其结果并不是准确的,而是一个近似值。
Shard Size
为了提高该聚合的精确度,可以通过shard_size参数设置协调节点向各个分片请求的词根个数,然后在协调节点进行聚合,最后只返回size个词根给到客户端,shard_size >= size,如果shard_size设置小于size,ES会自动将其设置为size,默认情况下shard_size建议设置为(1.5 * size + 10)。
Calculating Document Count Error
为了阐述返回结果中的doc_count_error_upper_bound、sum_other_doc_count代表什么意思,我们通过如下例子来说明Term Aggregations的工作机制。
根据这些返回的结果,在协调节点上聚合,最终得出如下响应结果:
1{
2 ...
3 "aggregations" : {
4 "products" : {
5 "doc_count_error_upper_bound" : 46,
6 "sum_other_doc_count" : 79,
7 "buckets" : [
8 {
9 "key" : "Product A",
10 "doc_count" : 100
11 },
12 {
13 "key" : "Product Z",
14 "doc_count" : 52
15 }
16 {
17 "key" : "Product C",
18 "doc_count" : 50
19 }
20 {
21 "key" : "Product G",
22 "doc_count" : 45
23 }
24 ...
25 ]
26 }
27 }
28}
那doc_count_error_upper_bound、sum_other_doc_count又分别代表什么呢?
doc_count_error_upper_bound
该值表示未进入最终术语列表的术语的最大潜在文档计数。这是根据从每个碎片返回的上一项的文档计数之和计算的(协调节点根据每个分片节点返回的最后一条数据相加得来的)。这意味着在最坏的情况下,没有返回的词根的最大文档个数为46个,在此次聚合结果中排名第4。
sum_other_doc_count
未纳入本次聚合结果中的文档总数量,这个容易理解。
Per bucket Document Count Error
每个桶的错误文档数量,可以通过参数show_term_doc_count_error=true来展示每个文档未被纳入结果集的数量。
其使用示例如下:
1GET /_search
2{
3 “aggs” : {
4 “products” : {
5 “terms” : {
6 “field” : “product”,
7 “size” : 5,
8 “show_term_doc_count_error”: true
9 }
10 }
11 }
12}
对应的返回值:
1{
2 ...
3 "aggregations" : {
4 "products" : {
5 "doc_count_error_upper_bound" : 46,
6 "sum_other_doc_count" : 79,
7 "buckets" : [
8 {
9 "key" : "Product A",
10 "doc_count" : 100,
11 "doc_count_error_upper_bound" : 0
12 },
13 {
14 "key" : "Product Z&