TypechoJoeTheme

IT技术分享

统计

07. ES分组统计查询——ElasticSearch搜索专栏

2022-06-16
/
0 评论
/
797 阅读
/
正在检测是否收录...
06/16

一、各组的总条数

在SQL语句中有group by,而在Elasticsearch中把它叫Aggregation,即聚合运算

GET /dbindex/_search
{
  "size": 0,
  "aggs": {
    "group_by_address": {
      "terms": {
        "field": "address.keyword"
      }
    }
  }
}

返回结果

{
  "took" : 2,
  "timed_out" : false,
  …
  "hits" : {
    "total" : {
      "value" : 4, // 统计总条数
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "group_by_address" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "上海",
          "doc_count" : 2
        },
        {
          "key" : "杭州",
          "doc_count" : 2
        }
      ]
    }
  }
}

二、每组的平均值

GET /dbindex/_search
{
  "size": 0,
  "aggs": {
    "group_by_address": {
      "terms": {
        "field": "address.keyword"
      },
    "aggs": {
        "score_avg": {
          "avg": {
            "field": "score"
          }
        }
      }
    }
  }
}

返回结果

{
  "took" : 6,
   …
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "group_by_address" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "上海",
          "doc_count" : 2,
          "score_avg" : {
            "value" : 75.0
          }
        },
        {
          "key" : "杭州",
          "doc_count" : 2,
          "score_avg" : {
            "value" : 75.0
          }
        }
      ]
    }
  }
}

三、每组的最大值

GET /dbindex/_search
{
  "size": 0,
  "aggs": {
    "group_by_address": {
      "terms": {
        "field": "address.keyword"
      },
    "aggs": {
        "score_max": {
          "max": {
            "field": "score"
          }
        }
      }
    }
  }
}

四、每组的最小值

GET /dbindex/_search
{
  "size": 0,
  "aggs": {
    "group_by_address": {
      "terms": {
        "field": "address.keyword"
      },
    "aggs": {
        "score_min": {
          "min": {
            "field": "score"
          }
        }
      }
    }
  }
}

五、每组的总和

GET /dbindex/_search
{
  "size": 0,
  "aggs": {
    "group_by_address": {
      "terms": {
        "field": "address.keyword"
      },
    "aggs": {
        "score_sum": {
          "sum": {
            "field": "score"
          }
        }
      }
    }
  }
}

六、每组的最小值并排序

GET /dbindex/_search
{
  "size": 0,
  "aggs": {
    "group_by_address": {
      "terms": {
        "field": "address.keyword",
        "order": {
          "score_min": "desc"
        }
      },
    "aggs": {
        "score_min": {
          "min": {
            "field": "score"
          }
        }
      }
    }
  }
}
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/2889/(转载时请注明本文出处及文章链接)