elasticsearch 权威指南聚合阅读笔记(四)

count(1)

select clssId,count(1) from student group by  classId

{
  "size":0,
  "aggs": {
    "group_by_classId": {
      "terms": {
        "field": "classId.keyword"
      }
    }
  }
}

结果 key为classId  doc_count 为count

size 0表示只看聚合结果不看搜索结果

{
    "took": 82,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 4,
        "max_score": 0,
        "hits": []
    },
    "aggregations": {
        "group_by_classId": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "2",
                    "doc_count": 3
                },
                {
                    "key": "5",
                    "doc_count": 1
                }
            ]
        }
    }
}

count+avg

select clssId,count(1),avg(score) from student group by  classId

{
  "size":0,
  "aggs": {
    "group_by_classId": {
      "terms": {
        "field": "classId.keyword"
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "score"
          }
        }
      }
    }
  }
}

结果

{
    "took": 95,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 4,
        "max_score": 0,
        "hits": []
    },
    "aggregations": {
        "group_by_classId": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "2",
                    "doc_count": 3,
                    "average_balance": {
                        "value": 53.333333333333336
                    }
                },
                {
                    "key": "5",
                    "doc_count": 1,
                    "average_balance": {
                        "value": 10
                    }
                }
            ]
        }
    }
}

聚合并排序

select clssId,count(1),avg(score) from student group by  classId order by  avg(score)  desc

{
  "size":0,
  "aggs": {
    "group_by_classId": {
      "terms": {
        "field": "classId.keyword",
        "order": {
          "average_score": "desc"
        }
      },
      "aggs": {
        "average_score": {
          "avg": {
            "field": "score"
          }
        }
      }
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/LQBlog/p/10539245.html