即使是不成熟的尝试,也胜于胎死腹中的策略。

elasticsearch es如何统计用户文档数量范围内容聚合?

匿名 | 发布于2022年05月28日 | 阅读数:2273

有个用户任务完成数据,格式如下:
id    uid  score time
11     2         1     2022-05-17 18:18:16
12     3          6     2022-05-17 17:17:15
13     2          7     2022-05-17 16:16:13
10     2         9      2022-05-16 10:15:12
17     6         10      2022-05-15 09:14:11
16     4         2      2022-05-15 05:12:11
15     3         3      2022-05-15 06:10:11
.......
 
需求 :统计完成次数  2-3次 这个范围的用户人数(1000万左右),分数总和,每天完成任务次数走势图。
满足这个条件 只有uid 2 和 uid3 ,一共2人(可近似值),这2人分数合计26分,按天走势 [2022-05-15,1],[2022-05-16,1],[2022-05-17,3]
 
已邀请:

laoyang360 - 《一本书讲透Elasticsearch》作者,Elastic认证工程师 [死磕Elasitcsearch]知识星球地址:http://t.cn/RmwM3N9;微信公众号:铭毅天下; 博客:https://elastic.blog.csdn.net

赞同来自:

 
DELETE task-index-001
PUT task-index-001
{
"mappings": {
"properties": {
"id": {
"type": "integer"
},
"uid": {
"type": "integer"
},
"score": {
"type": "integer"
},
"time":{
"type": "date",
"format": ["yyyy-MM-dd HH:mm:ss"]
}
}
}
}
POST task-index-001/_bulk
{"index":{"_id":1}}
{"id":11,"uid":2,"score":1,"time":"2022-05-27 18:18:16"}
{"index":{"_id":2}}
{"id":12,"uid":3 ,"score":6,"time":"2022-05-20 17:17:15"}
{"index":{"_id":3}}
{"id":13,"uid":2,"score":7,"time":"2022-05-18 16:16:13"}
{"index":{"_id":4}}
{"id":10,"uid":2,"score":9,"time":"2022-05-16 10:15:12"}
{"index":{"_id":5}}
{"id":17,"uid":6,"score":10,"time":"2022-05-15 09:14:11"}
{"index":{"_id":6}}
{"id":16 ,"uid":4,"score":2,"time":"2022-05-15 05:12:11"}
{"index":{"_id":7}}
{"id":15,"uid":3,"score":3,"time":"2022-05-11 06:10:11"}



POST task-index-001/_search
{
"size": 0,
"aggs": {
"terms_aggs": {
"terms": {
"field": "uid",
"size": 10,
"min_doc_count": 2
},
"aggs": {
"sum_aggs": {
"sum": {
"field": "score"
}
}
}
},
"sum_all": {
"sum_bucket": {
"buckets_path": "terms_aggs>sum_aggs"
}
}
}
}

FFFrp

赞同来自:

可以加个字段标识当前用户总次数吗,这样可以在query里面过滤了

Charele - Cisco4321

赞同来自:

我有个想法,不知可否。
先查出 count(uid) as uidCnt, sum(score) as scoreSum group by uid(这个应该简单)
 
然后结果直接插入另外一个新索引,文档_id就是uid,相同_id会覆盖.
(也可只插入部分结果,比如uidCnt在2,3之间的。看需求)。
 
有了这个新索引,实现你的查询要求就很简单了。
 
 

要回复问题请先登录注册