跳到主要内容

十五、Elasticsearch 教程: 聚合计算

聚合框架用于收集搜索查询选择的所有数据。该框架由许多构建块组成,有助于构建复杂的数据摘要

下面的JSON 对象使用聚合函数的一般请求正文格式

"aggregations" : {
"<aggregation_name>" : {
"<aggregation_type>" : {
<aggregation_body>
}
[,"meta" : { [<meta_data_body>] } ]?
[,"aggregations" : { [<sub_aggregation>]+ } ]?
}

Elasticsearch 提供了大量的聚合函数,它们都有各自不同的目的

矩阵聚合 ( Metrics )

这些聚合函数可以根据聚合文档的字段值计算度量值,而且有时可以从脚本生成一些值

数字矩阵既可以是单值,也可以是平均聚合或多值统计等

平均数聚合 ( avg )

该聚合函数用于计算文档中出现的任何数字字段的平均值

例如

POST http://localhost:9200/user_admin/_search?pretty

请求正文

{
"aggs":{
"avg_money":{"avg":{"field":"money"}}
}

返回响应结果

{
"took" : 160,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 3,
"max_score" : 1.0,
"hits" : [
{
"_index" : "user_admin",
"_type" : "user",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"nickname" : "雅少",
"description" : "虚怀若谷",
"street" : "四川大学",
"city" : "Chengdu",
"state" : "Sichuan",
"zip" : "610044",
"location" : [
104.094537,
30.640174
],
"money" : 68023,
"tags" : [
"Python",
"HTML"
],
"vitality" : "7.8"
}
},
{
"_index" : "user_admin",
"_type" : "user",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"nickname" : "站长",
"description" : "pottercoding.cn 程序员波特,程序员编程资料站 ,教程 ",
"street" : "东四十条",
"city" : "Beijing",
"state" : "Beijing",
"zip" : "100007",
"location" : [
116.432727,
39.937732
],
"money" : 5201814,
"tags" : [
"PHP",
"Python"
],
"vitality" : "9.0"
}
},
{
"_index" : "user_admin",
"_type" : "user",
"_id" : "3",
"_score" : 1.0,
"_source" : {
"nickname" : "歌者",
"description" : "程序设计也是设计,研发新菜也是研发",
"street" : "五道口",
"city" : "Beijing",
"state" : "Beijing",
"zip" : "100083",
"location" : [
116.346346,
39.999333
],
"money" : 71128,
"tags" : [
"Java",
"Scala"
],
"vitality" : "6.9"
}
}
]
},
"aggregations" : {
"avg_money" : {
"value" : 1780321.6666666667
}
}