如何在 Elastic 搜索中按月分组
How to group by month in Elastic search
我正在使用弹性搜索版本 6.0.0
对于按月分组,我使用日期直方图聚合。
我试过的例子:
{
"from":0,
"size":2000,
"_source":{
"includes":[
"cost",
"date"
],
"excludes":[
],
"aggregations":{
"date_hist_agg":{
"date_histogram":{
"field":"date",
"interval":"month",
"format":"M",
"order":{
"_key":"asc"
},
"min_doc_count":1
},
"aggregations":{
"cost":{
"sum":{
"field":"cost"
}
}
}
}
}
}
}
结果我多次得到 1(Jan/January)。
由于我有 2016 年 1 月、2017 年 1 月、2018 年 1 月的数据,因此 return 3 次一月。但我只想要一月一次,其中包含一月所有年份的总和。
您可以使用 terms
聚合和从日期中提取月份的脚本,而不是使用 date_histogram
聚合。
{
"from": 0,
"size": 2000,
"_source": {"includes": ["cost","date"],"excludes"[]},
"aggregations": {
"date_hist_agg": {
"terms": {
"script": "doc['date'].date.monthOfYear",
"order": {
"_key": "asc"
},
"min_doc_count": 1
},
"aggregations": {
"cost": {
"sum": {
"field": "cost"
}
}
}
}
}
}
请注意,使用脚本并不是最佳选择,如果您知道自己需要月份信息,只需使用该信息创建另一个字段,这样您就可以在其上使用简单的术语聚合,而无需使用脚本。
我正在使用弹性搜索版本 6.0.0 对于按月分组,我使用日期直方图聚合。 我试过的例子:
{
"from":0,
"size":2000,
"_source":{
"includes":[
"cost",
"date"
],
"excludes":[
],
"aggregations":{
"date_hist_agg":{
"date_histogram":{
"field":"date",
"interval":"month",
"format":"M",
"order":{
"_key":"asc"
},
"min_doc_count":1
},
"aggregations":{
"cost":{
"sum":{
"field":"cost"
}
}
}
}
}
}
}
结果我多次得到 1(Jan/January)。 由于我有 2016 年 1 月、2017 年 1 月、2018 年 1 月的数据,因此 return 3 次一月。但我只想要一月一次,其中包含一月所有年份的总和。
您可以使用 terms
聚合和从日期中提取月份的脚本,而不是使用 date_histogram
聚合。
{
"from": 0,
"size": 2000,
"_source": {"includes": ["cost","date"],"excludes"[]},
"aggregations": {
"date_hist_agg": {
"terms": {
"script": "doc['date'].date.monthOfYear",
"order": {
"_key": "asc"
},
"min_doc_count": 1
},
"aggregations": {
"cost": {
"sum": {
"field": "cost"
}
}
}
}
}
}
请注意,使用脚本并不是最佳选择,如果您知道自己需要月份信息,只需使用该信息创建另一个字段,这样您就可以在其上使用简单的术语聚合,而无需使用脚本。