Elasticsearch – 按组分组并计数

huangapple go评论53阅读模式
英文:

Elasticsearch - group by and count

问题

我想要使用Elasticsearch中的聚合功能来实现如下所示的目标:

部门 A: 2
部门 B: 1
英文:

I have the following index and data in Elasticsearch that stores the booking records.

student_id | department | room_booked | start_time
peter      | A          | 1           | 2023-05-01 12:00:00
peter      | A          | 3           | 2023-05-02 12:00:00
tom        | A          | 2           | 2023-05-02 12:00:00
mary       | B          | 1           | 2023-05-02 12:00:00

I want to get the number of unique users in each department like below:

department A: 2
department B: 1

How to achieve that using aggregation in Elasticsearch?

答案1

得分: 0

你首先需要使用terms聚合按部门进行聚合,然后在student_id字段上添加cardinality子聚合,以获取每个部门的学生的唯一计数:

{
  "size": 0,
  "aggs": {
    "depts": {
      "terms": {
        "field": "department"
      },
      "aggs": {
        "count": {
          "cardinality": {
            "field": "student_id"
          }
        }
      }
    }
  }
}
英文:

You first need to aggregate by department using a terms aggregation and then add a cardinality sub-aggregation on the student_id field to get the unique count of students per department:

{
  "size": 0,
  "aggs": {
    "depts": {
      "terms": {
        "field": "department"
      },
      "aggs": {
        "count": {
          "cardinality": {
            "field": "student_id"
          }
        }
      }
    }
  }
}

huangapple
  • 本文由 发表于 2023年5月25日 11:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定