英文:
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"
}
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论