ES实战-聚集

根据某字段值聚集返回统计数据

bash 复制代码
#curl 写法
curl 'localhost:9200/get-together/_search?pretty' -H 'Content-Type:application/json' -d '{
"aggs":{
	"top_tags":{
	"terms":{
		"field":"tags.verbatim"
		}
	}
}}'
# kibana主体写法
GET /get-together/_search
{
  "aggs": {
    "top_tags": {
      "terms": {
        "field": "tags.verbatim"
      }
    }
  }
}

Elasticsearch提供了多种聚合类型,用于不同的分析目的

1.terms聚合-适用于统计字段值的分布情况

2.avg:计算平均值。

3.sum:计算总和。

4.min和max:找到最小值和最大值。

5.histogram:按照数值区间分桶。

6.date_histogram:按照时间间隔分桶。

7.range:基于预定义的范围分桶。

8.cardinality:计算字段的基数(不同值的数量)。

等等。
在指定查询条件情况下聚合

bash 复制代码
GET /get-together/_search
{
  "query": {
    "match": {
      "name":"Denver"
    }
  }, 
  "aggs": {
    "top_tags": {
      "terms": {
        "field": "tags.verbatim"
      }
    }
  }
}

聚合某个数组类型的字段

bash 复制代码
#其中的stats 还可以换成avg min max sum value_count
GET /get-together/_search?pretty
{
  "size": 0,
  "aggs": {
    "attendees_stats": {
      "stats": {
        "script": {
          "source": "doc['attendees'].size()"
        }
      }
    }
  }
}
#使用extended_stats 聚合获取平方,方差,标准差
GET /get-together/_search?pretty
{
  "size": 0,
  "aggs": {
    "attendees_stats": {
      "extended_stats": {
        "script": {
          "source": "doc['attendees'].size()"
        }
      }
    }
  }
}

Percentiles 聚合

bash 复制代码
#percentiles聚合用于计算一个字段的百分位数,可以帮助你了解数据的分布。
GET /_search
{
  "aggs": {
    "grade_percentiles": {
      "percentiles": {
        "field": "grade",
        "percents": [25, 50, 75]  // 可以指定需要的百分位数
      }
    }
  }
}

Percentile Ranks 聚合

bash 复制代码
#percentile_ranks聚合显示了值在数据分布中的排名百分位。
GET /_search
{
  "aggs": {
    "grade_percentile_ranks": {
      "percentile_ranks": {
        "field": "grade",
        "values": [60, 70, 80]  // 你想知道这些值的百分位排名
      }
    }
  }
}

Cardinality 聚合

bash 复制代码
#cardinality聚合用于计算字段中不同值的数量,类似于SQL中的COUNT(DISTINCT field)。
GET /_search
{
  "aggs": {
    "unique_grades": {
      "cardinality": {
        "field": "grade"
      }
    }
  }
}
相关推荐
未济1 天前
linux 配置环境变量
linux
傲世仙尊1 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
_艾伦 耶格尔.1 天前
进程间通信
linux
Liuqy-051 天前
Linux IO编程——静态库、动态库
linux
彧azz1 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅1 天前
linux(8) 软硬链接
linux·运维·服务器
AIgorithmGEEK1 天前
[Linux]线程三部曲(上):一个执行流的诞生——从操作系统一路拆到 pthread_create
linux·线程·pid
Elasticsearch1 天前
Elastic Observability 的跨项目搜索:通过一个查询搜索所有关联项目
elasticsearch
琥珀色糖1 天前
SimlpeHttp
linux·服务器
qeen871 天前
【Linux】操作系统之进程介绍(二)
linux·笔记·学习·进程