gpt4 book ai didi

elasticsearch - 按日期和类别 Elasticsearch 查询分组

转载 作者:行者123 更新时间:2023-11-29 02:47:10 25 4
gpt4 key购买 nike

我在 elasticsearch 中有一个索引并导入了下面的 json 文件:

{"index" : {"_id": "1"}}
{"Name": "apple","Type": "fruit","Rate": "64","Date": "2016-01-24"}
{"index" : {"_id": "2"}}`enter code here`
{"Name": "grape","Type": "fruit","Rate": "100","Date": "2016-01-21"}
{"index" : {"_id": "3"}}
{"Name": "banana","Type": "fruit","Rate": "72","Date": "2016-01-14"}
{"index" : {"_id": "4"}}
{"Name": "orange","Type": "fruit","Rate": "82","Date": "2016-01-13"}
{"index" : {"_id": "5"}}
{"Name": "mango","Type": "fruit","Rate": "53","Date": "2016-02-16"}
{"index" : {"_id": "6"}}
{"Name": "grapes","Type": "fruit","Rate": "56","Date": "2016-02-18"}
{"index" : {"_id": "7"}}
{"Name": "blueberry","Type": "fruit","Rate": "96","Date": "2016-02-25"}
{"index" : {"_id": "8"}}
{"Name": "watermelon","Type": "fruit","Rate": "124","Date": "2016-02-12"}
{"index" : {"_id": "9"}}
{"Name": "papaya","Type": "fruit","Rate": "75","Date": "2016-03-09"}
{"index" : {"_id": "10"}}
{"Name": "carrot","Type": "vegetable","Rate": "25","Date": "2016-01-21"}
{"index" : {"_id": "11"}}
{"Name": "ladyfinger","Type": "vegetable","Rate": "89","Date": "2016-01-26"}
{"index" : {"_id": "12"}}
{"Name": "potato","Type": "vegetable","Rate": "36","Date": "2016-02-14"}
{"index" : {"_id": "13"}}
{"Name": "tomato","Type": "vegetable","Rate": "45","Date": "2016-02-07"}
{"index" : {"_id": "14"}}
{"Name": "spinach","Type": "vegetable","Rate": "25","Date": "2016-02-24"}
{"index" : {"_id": "15"}}
{"Name": "raddish","Type": "vegetable","Rate": "21","Date": "2016-02-13"}
{"index" : {"_id": "16"}}
{"Name": "pumpkin","Type": "vegetable","Rate": "78","Date": "2016-03-10"}
{"index" : {"_id": "17"}}
{"Name": "lemon","Type": "vegetable","Rate": "98","Date": "2016-03-11"}

现在我想获得每个月每种类型的计数,直到现在我能够通过以下 elasticsearch 查询按类别找到总计数:

{
"size": 0,
"aggs": {
"group_by_Type": {
"terms": {
"field": "Type"
}
}
}
}

我希望这个计数按月划分。请帮忙

最佳答案

好的开始!现在你只需要使用 date_histogram aggregationinterval 设置为 month,然后将当前的 terms 聚合移动为 date_histogram 聚合的子聚合,基本上是这样的:

{
"size": 0,
"aggs": {
"group_by_month": {
"date_histogram": {
"field": "Date",
"interval": "month"
},
"aggs": {
"group_by_Type": {
"terms": {
"field": "Type"
}
}
}
}
}
}

更新

如果只想关注某个时间段,可以添加一个query来限制文档集聚合:

{
"size": 0,
"query": {
"range": {
"Date": {
"gte": "2016-01-01T00:00:00.000Z",
"lt": "2016-02-01T00:00:00.000Z"
}
}
},
"aggs": {
"group_by_month": {
"date_histogram": {
"field": "Date",
"interval": "month"
},
"aggs": {
"group_by_Type": {
"terms": {
"field": "Type"
}
}
}
}
}
}

关于elasticsearch - 按日期和类别 Elasticsearch 查询分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011856/

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