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"
      }
    }
  }
}
相关推荐
亚马逊云开发者11 分钟前
告别手动部署:在 Amazon EKS 上用 CodePipeline + Argo CD 搭建 GitOps CI/CD
elasticsearch·ci/cd·kubernetes
123过去23 分钟前
hashid使用教程
linux·网络·测试工具·安全
C+++Python35 分钟前
Linux/C++多进程
linux·运维·c++
Stack Overflow?Tan901 小时前
linux ubuntu22.04安装ROS2humble完整版的流程
linux·docker·ros2
zly35001 小时前
centos7 sshd无法启动
linux·运维·服务器
编程大师哥2 小时前
Linux 命名管道(FIFO)通信 超清晰讲解
linux·运维·服务器
Smile_2542204182 小时前
linux服务器清理磁盘
linux·运维·服务器
KivenMitnick3 小时前
Claude Code--Ubuntu Linux超详细配置教程(附每步的可能报错及解决方法)
linux·运维·ubuntu
Elastic 中国社区官方博客3 小时前
LINQ 到 ES|QL:使用 C# 查询 Elasticsearch
大数据·数据库·sql·elasticsearch·搜索引擎·全文检索·linq
panamera123 小时前
linux下SPI、IIC、UART、CAN的编码
linux·运维·服务器