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

1 - distinct
SELECT DISTINCT(user_id) FROM table WHERE user_id_type = 3;
{
“query”: {
“term”: {
“user_id_type”: 3
}
},
“collapse”: {
“field”: “user_id”
}
}
{

“hits”: {
“hits”: [
{
“_index”: “es_qd_mkt_visitor_packet_dev_v1_20180621”,
“_type”: “ad_crowd”,
“_source”: {
“user_id”: “wx2af8414b502d4ca2_oHtrD0Vxv-_8c678figJNHmtaVQQ”,
“user_id_type”: 3
},
“fields”: {
“user_id”: [
“wx2af8414b502d4ca2_oHtrD0Vxv-_8c678figJNHmtaVQQ”
]
}
}
]
}
}
总结:使用collapse字段后,查询结果中[hits]中会出现[fields]字段,其中包含了去重后的user_id

2 - count + distinct
SELECT COUNT(DISTINCT(user_id)) FROM table WHERE user_id_type = 3;
{
“query”: {
“term”: {
“user_id_type”: 3
}
},
“aggs”: {
“count”: {
“cardinality”: {
“field”: “user_id”
}
}
}
}
{

“hits”: {

},
“aggregations”: {
“count”: {
“value”: 121
}
}
}
总结:aggs中cardinality的字段代表需要distinct的字段

3 - count + group by
SELECT COUNT(user_id) FROM table GROUP BY user_id_type;
{
“aggs”: {
“user_type”: {
“terms”: {
“field”: “user_id_type”
}
}
}
}
{

“hits”: {

},
“aggregations”: {
“user_type”: {

“buckets”: [
{
“key”: 4,
“doc_count”: 1220
},
{
“key”: 3,
“doc_count”: 488
}
]
}
}
}
总结:aggs中terms的字段代表需要gruop by的字段

4 - count + distinct + group by
SELECT COUNT(DISTINCT(user_id)) FROM table GROUP BY user_id_type;
{
“aggs”: {
“user_type”: {
“terms”: {
“field”: “user_id_type”
},
“aggs”: {
“count”: {
“cardinality”: {
“field”: “user_id”
}
}
}
}
}
}
{

“hits”: {

},
“aggregations”: {
“user_type”: {

“buckets”: [
{
“key”: 4,
“doc_count”: 1220, //去重前数据1220条
“count”: {
“value”: 276 //去重后数据276条
}
},
{
“key”: 3,
“doc_count”: 488, //去重前数据488条
“count”: {
“value”: 121 //去重后数据121条
}
}
]
}
}
}
5 - count + distinct + group by + where
SELECT COUNT(DISTINCT(user_id)) FROM table WHERE user_id_type = 2 GROUP BY user_id;
总结:对于既有group by又有distinct的查询要求,需要在aggs中嵌套子aggs

6 - 注意事项
collapse关键字

折叠功能ES5.3版本之后才发布的。
聚合&折叠只能针对keyword类型有效;

作者:彬彬酱
链接:https://www.jianshu.com/p/62bed9cc8349
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值