elasticsearch global 、 filters 和 cardinality 聚合

震耳欲聋
• 阅读 882

1. 背景

此处将单记录一下 globalfilterscardinality的聚合操作。

2、解释

1、global

global聚合是全局聚合,是对所有的文档进行聚合,而不受查询条件的限制。

global 聚合器只能作为顶级聚合器,因为将一个 global 聚合器嵌入另一个桶聚合器是没有意义的。

比如: 我们有50个文档,通过查询条件筛选之后存在10个文档,此时我想统计总共有多少个文档。是50个,因为global统计不受查询条件的限制。

2、filters

定义一个多桶聚合,其中每个桶都与一个过滤器相关联。每个桶都会收集与其关联的过滤器匹配的所有文档。

比如: 我们总共有50个文档,通过查询条件筛选之后存在10个文档,此时我想统计 这10个文档中,出现info词语的文档有多少个,出现warn词语的文档有多少个。

3、cardinality

类似于 SQL中的 COUNT(DISTINCT(字段)),不过这个是近似统计,是基于 HyperLogLog++ 来实现的。

3、需求

我们有一组日志,每条日志都存在idmessage2个字段。此时根据message字段过滤出存在info warn的日志,然后进行统计:

  1. 系统中总共有多少条日志(global + cardinality)
  2. info和warn级别的日志各有多少条(filters)

4、前置条件

4.1 创建mapping

PUT /index_api_log
{
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "properties": {
      "message":{
        "type": "text"
      },
      "id": {
        "type": "long"
      }
    }
  }
}

4.2 准备数据

PUT /index_api_log/_bulk
{"index":{"_id":1}}
{"message": "this is info message-01","id":1}
{"index":{"_id":2}}
{"message": "this is info message-02","id":2}
{"index":{"_id":3}}
{"message": "this is warn message-01","id":3}
{"index":{"_id":4}}
{"message": "this is error message","id":4}
{"index":{"_id":5}}
{"message": "this is info and warn message","id":5}

5、实现3的需求

5.1 dsl

POST /index_api_log/_search
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "message": "info warn"
          }
        }
      ]
    }
  }, 
  "aggregations": {
    "agg_01": {
      "filters": {
        "filters": {
          "info": {
            "match": {
              "message": "info"
            }
          },
          "warn": {
            "match": {
              "message": "warn"
            }
          }
        },
        "other_bucket": true,
        "other_bucket_key": "other"
      }
    },
    "agg_02":{
      "global": {},
      "aggs": {
        "total": {
          "cardinality": {
            "field": "id",
            "precision_threshold": 30000
          }
        }
      }
    }
  }
}

5.2 java 代码

@Test
@DisplayName("global and filters and cardinality 聚合")
public void test01() throws IOException {
    SearchRequest request = SearchRequest.of(searchRequest ->
            searchRequest.index("index_api_log")
                    // 查询 message 中存在 info 和 warn 的日志
                    .query(query -> query.bool(bool -> bool.must(must -> must.match(match -> match.field("message").query("info warn")))))
                    // 查询的结果不返回
                    .size(0)
                    // 第一个聚合
                    .aggregations("agg_01", agg ->
                            agg.filters(filters ->
                                    filters.filters(f ->
                                                    f.array(
                                                            Arrays.asList(
                                                                    // 在上一步query的结果中,将 message中包含info的进行聚合
                                                                    Query.of(q -> q.match(m -> m.field("message").query("info"))),
                                                                    // 在上一步query的结果中,将 message中包含warn的进行聚合
                                                                    Query.of(q -> q.match(m -> m.field("message").query("warn")))
                                                            )
                                                    )
                                            )
                                            // 如果上一步的查询中,存在非 info 和 warn的则是否聚合到 other 桶中
                                            .otherBucket(true)
                                            // 给 other 桶取一个名字
                                            .otherBucketKey("other")
                            )
                    )
                    // 第二个聚合
                    .aggregations("agg_02", agg ->

                            agg
                                    // 此处的 global 聚合只能放在顶部
                                    .global(global -> global)
                                    // 子聚合,数据来源于所有的文档,不受上一步query结果的限制
                                    .aggregations("total", subAgg ->
                                            // 类似于SQL中的 count(distinct(字段)),是一个近似统计
                                            subAgg.cardinality(cardinality ->
                                                    // 统计的字段
                                                    cardinality.field("id")
                                                            // 精度,默认值是30000,最大值也是40000,不超过这个值的聚合近似准确值
                                                            .precisionThreshold(30000)
                                            )
                                    )
                    )
    );
    System.out.println("request: " + request);
    SearchResponse<String> response = client.search(request, String.class);
    System.out.println("response: " + response);
}

5.3 运行结果

elasticsearch global 、 filters 和 cardinality 聚合

6、实现代码

https://gitee.com/huan1993/spring-cloud-parent/blob/master/es/es8-api/src/main/java/com/huan/es8/aggregations/bucket/GlobalAndFiltersAggs.java

7、参考文档

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

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Peter20 Peter20
4年前
mysql中like用法
like的通配符有两种%(百分号):代表零个、一个或者多个字符。\(下划线):代表一个数字或者字符。1\.name以"李"开头wherenamelike'李%'2\.name中包含"云",“云”可以在任何位置wherenamelike'%云%'3\.第二个和第三个字符是0的值wheresalarylike'\00%'4\
Stella981 Stella981
3年前
List的Select 和Select().tolist()
List<PersondelpnewList<Person{newPerson{Id1,Name"小明1",Age11,Sign0},newPerson{Id2,Name"小明2",Age12,
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Stella981 Stella981
3年前
JavaScript常用函数
1\.字符串长度截取functioncutstr(str,len){vartemp,icount0,patrn/^\x00\xff/,strre"";for(vari
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这