ES中的聚合搜索可以理解为关系型数据库中的group by,将具有相同条件的数据分组,并分析每一组数据的不同表现。
high-level concepts
要理解什么是聚合查询(统计) 需要了解下边的两个重要的概念。
Buckets
GET /cars/transactions/_search?search_type=countYou’ll notice that we used the
{
"aggs" : {这是一个聚合查询
"colors" : {此聚合查询的名字(自己定义)
"terms" : {
"field" : "color"定义聚合条件。以color分组
}
}
}
}
count
search_type
.
Because we don’t care about search results—the aggregation totals—the
count
search_type will be faster because it omits the fetch phase.
在讲query 执行时,elasticsearch会分为两个阶段,query阶段,fetch阶段。我们并不需要查询结果,只需要知道统计结果,所以省去了fetch阶段,search_type=count使聚合查询更高效
{
...
"hits": {
"hits": []没有数据是因为我们search_type=count 并没有fetch阶段
},
"aggregations": {
"colors": {你定义的聚合查询的名字
"buckets": [
{
"key": "red",红色分组
"doc_count": 4符合此条件的文档数
},
{
"key": "blue",
"doc_count": 2
},
{
"key": "green",
"doc_count": 2
}
]
}
}
}
adding a metric to the mix
GET /cars/transactions/_search?search_type=count
{
"aggs": {
"colors": {
"terms": {
"field": "color"
},
"aggs": {最外层是aggs,用来包裹住我们的统计条件
"avg_price": {统计名称
"avg": {
"field": "price"我们将计算每组的price平均值
}
}
}
}
}
}
buckets inside buckets
分组数据的嵌套,group by color,make 先按 color分组,再按make分组
GET /cars/transactions/_search?search_type=count
{
"aggs": {
"colors": {
"terms": {
"field": "color"
},
"aggs": {
"avg_price": {注意它的顺序。他统计的平均值,是紧接的上一个条件的统计值
"avg": {
"field": "price"
}
},
"make": {
"terms": {
"field": "make"
}
}
}
}