ElasticSearch中”distinct”,”count”和”group by”的实现

参考地址:https://www.jianshu.com/p/62bed9cc8349

1 – distinct

SELECT DISTINCT(user_id) FROM table WHERE user_id_type = 3;

[cc lang=”php”]
{
“query”: {
“term”: {
“user_id_type”: 3
}
},
“collapse”: {
“field”: “user_id”
}
}
[/cc]

总结:使用collapse字段后,查询结果中[hits]中会出现[fields]字段,其中包含了去重后的user_id

2 – count + distinct

SELECT COUNT(DISTINCT(user_id)) FROM table WHERE user_id_type = 3;

[cc lang=”php”]
{
“query”: {
“term”: {
“user_id_type”: 3
}
},
“aggs”: {
“count”: {
“cardinality”: {
“field”: “user_id”
}
}
}
}
[/cc]

总结:aggs中cardinality的字段代表需要distinct的字段

3 – count + group by

SELECT COUNT(user_id) FROM table GROUP BY user_id_type;

[cc lang=”php”]
{
“aggs”: {
“user_type”: {
“terms”: {
“field”: “user_id_type”
}
}
}
}
[/cc]

4 – count + distinct + group by

SELECT COUNT(DISTINCT(user_id)) FROM table GROUP BY user_id_type;

[cc lang=”php”]
{
“aggs”: {
“user_type”: {
“terms”: {
“field”: “user_id_type”
},
“aggs”: {
“count”: {
“cardinality”: {
“field”: “user_id”
}
}
}
}
}
}
[/cc]

You May Also Like

About the Author: daidai5771

发表评论

电子邮件地址不会被公开。 必填项已用*标注