gpt4 book ai didi

elasticsearch - 日期基数直方图

转载 作者:行者123 更新时间:2023-11-29 02:51:50 24 4
gpt4 key购买 nike

查询 Elasticsearch 以实现表示唯一身份访问者总数指标的日期直方图的最佳方式是什么?

考虑以下数据:

PUT /events
{
"mappings" : {
"_doc" : {
"properties" : {
"userId" : { "type" : "keyword" },
"eventDate" : { "type" : "date" }
}
}
}
}

POST /events/_bulk
{ "index" : { "_index" : "events", "_type" : "_doc", "_id" : "1" } }
{"userId": "1","eventDate": "2019-03-04T13:40:18.514Z"}
{ "index" : { "_index" : "events", "_type" : "_doc", "_id" : "2" } }
{"userId": "2","eventDate": "2019-03-04T13:46:18.514Z"}
{ "index" : { "_index" : "events", "_type" : "_doc", "_id" : "3" } }
{"userId": "3","eventDate": "2019-03-04T13:50:18.514Z"}
{ "index" : { "_index" : "events", "_type" : "_doc", "_id" : "4" } }
{"userId": "1","eventDate": "2019-03-05T13:46:18.514Z"}
{ "index" : { "_index" : "events", "_type" : "_doc", "_id" : "5" } }
{"userId": "4","eventDate": "2019-03-05T13:46:18.514Z"}

现在,如果我查询 userId 字段的基数,我会得到 4 个不同的访问者。

POST /events/_search
{
"size": 0,
"aggs": {
"visitors": {
"cardinality": {
"field": "userId"
}
}
}
}

但是,根据日期直方图分布文档时,我得到的总和为 5,因为两个存储桶中都有重复的 userId。

POST /events/_search
{
"size": 0,
"aggs": {
"visits_over_time": {
"date_histogram": {
"field": "eventDate",
"interval": "1d"
},
"aggs": {
"visitors": {
"cardinality": {
"field": "userId"
}
}
}
}
}
}

有没有办法过滤掉那些重复的值?实现这一目标的最佳方法是什么?

最佳答案

我们在代码中遇到了同样的问题,我们的解决方案是在 UserId 字段上使用 Terms 聚合,在 datetime 字段上使用嵌套的 Min 聚合。这为您提供了一个包含第一次访问的 Bucket 的每个 userId 的 bucket。我们在日期直方图之外进行聚合,然后手动映射。

"aggs": {
"UniqueUsers": {
"terms": {
"field": "userId",
"size": 1000,
}, "aggs": {
"FirstSeen": {
"min": {
"field": "date"
}
}
}
}
}

这对我们有用,但我相信应该有更好的实现方式。

关于elasticsearch - 日期基数直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55101843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com