【ES】学习10-聚合3

聚合是在查询匹配的文档中做统计的

不指定查询语句时,从所有文档中匹配。

下面两个语句等价:

GET /cars/transactions/_search
{
    "size" : 0,
    "aggs" : {
        "colors" : {
            "terms" : {
              "field" : "color"
            }
        }
    }
}
GET /cars/transactions/_search
{
    "size" : 0,
    "query" : {
        "match_all" : {}
    },
    "aggs" : {
        "colors" : {
            "terms" : {
              "field" : "color"
            }
        }
    }
}

 

全局桶:global

一个包含所有数据的桶,可以在即想使用子集,又想使用全集时用到。

GET /cars/transactions/_search
{
    "size" : 0,
    "query" : {
        "match" : {
            "make" : "ford"
        }
    },
    "aggs" : {
        "single_avg_price": {
            "avg" : { "field" : "price" } 
        },
        "all": {
            "global" : {}, 
            "aggs" : {
                "avg_price": {
                    "avg" : { "field" : "price" } 
                }

            }
        }
    }
}

 

一个同时包括过滤和聚合的例子

GET /cars/transactions/_search
{
    "size" : 0,
    "query" : {
        "constant_score": {
            "filter": {
                "range": {
                    "price": {
                        "gte": 10000
                    }
                }
            }
        }
    },
    "aggs" : {
        "single_avg_price": {
            "avg" : { "field" : "price" }
        }
    }
}

 

 

过滤桶:filter

只有查询结果中符合条件的文档才会放入过滤桶,用于对聚合结果过滤

GET /cars/transactions/_search
{
   "size" : 0,
   "query":{
      "match": {
         "make": "ford"
      }
   },
   "aggs":{
      "recent_sales": {
         "filter": { 
            "range": {
               "sold": {
                  "from": "now-1M"
               }
            }
         },
         "aggs": {
            "average_price":{
               "avg": {
                  "field": "price" 
               }
            }
         }
      }
   }
}

 

后过滤器:post_filter

只过滤搜索结果,不过滤聚合结果

说实话,例子我没看懂。感觉短期内用不上,先跳过了。

 

posted @ 2017-06-15 19:11  匡子语  阅读(349)  评论(0编辑  收藏  举报