参考地址: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]