2、elasticsearch聚合条件

聚合可以获取搜获结果中的元信息

GET /customer/_search
{
  "size": 0,
  "aggs": {
    "group_by_status": {
      "terms": {
        "field": "age",
        "size": 10
      }
    }
  }
}

结果如下

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "group_by_status" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 16,
          "doc_count" : 1
        },
        {
          "key" : 29,
          "doc_count" : 1
        }
      ]
    }
  }
}

也可以聚合复杂条件,比如求年龄平均值

GET /customer/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "name.keyword"
      },
    "aggs":{
      "average_balance":{
        "avg": {
          "field": "age"
        }
      }
    }
    }
  }
}

请求结果

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "group_by_state" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "Qing Liu",
          "doc_count" : 2,
          "average_balance" : {
            "value" : 39.5
          }
        },
        {
          "key" : "Jared Zhang",
          "doc_count" : 1,
          "average_balance" : {
            "value" : 16.0
          }
        }
      ]
    }
  }
}

以下是使用聚合条件排序,而不用聚合结果排序

GET /customer/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "name.keyword"
        , "order": {
          "average_balance": "asc"
        }
      },
    "aggs":{
      "average_balance":{
        "avg": {
          "field": "age"
        }
      }
    }
    }
  }
}

你可能感兴趣的:(2、elasticsearch聚合条件)