Skip to main content

日期范围聚合 date_range

Date Range Aggregation

专用于日期值的范围聚合。此聚合与正常范围聚合之间的主要区别在于,from和to值可以用Date Math表达式表示,还可以指定返回from和to响应字段的日期格式。

POST /sales/_search?size=0
{
"aggs": {
"range": {
"date_range": {
"field": "date",
"format": "MM-yyyy",
"ranges": [
{ "to": "now-10M/M" },
{ "from": "now-10M/M" }
]
}
}
}
}

在上面的示例中,我们创建了两个范围桶,第一个“桶”为所有日期在10个月之前的文档,第二个“桶”为所有日期为10个月之后的文档

{
...
"aggregations": {
"range": {
"buckets": [
{
"to": 1.4436576E12,
"to_as_string": "10-2015",
"doc_count": 7,
"key": "*-10-2015"
},
{
"from": 1.4436576E12,
"from_as_string": "10-2015",
"doc_count": 0,
"key": "10-2015-*"
}
]
}
}
}

Missing Values

缺失值处理

POST /sales/_search?size=0
{
"aggs": {
"range": {
"date_range": {
"field": "date",
"missing": "1976/11/30",
"ranges": [
{
"key": "Older",
"to": "2016/02/01"
},
{
"key": "Newer",
"from": "2016/02/01",
"to" : "now/d"
}
]
}
}
}
}

日期字段中没有值的文档将被添加到“Older”存储桶中。

Date Format/Pattern

参照JodaDate 其定义如下:

符号含义介绍示例值
GeratextAD
Ccentury of era (>=0)number20
Yyear of era (>=0)year1996
xweekyearyear1996
wweek of weekyearnumber27
eday of weeknumber2
Eday of weektextTuesday; Tue
yyearyear1996
Dday of yearnumber189
Mmonth of yearmonthJuly; Jul; 07
dday of monthnumber10
ahalfday of daytextPM
Khour of halfday (0~11)number0
hclockhour of halfday (1~12)number12
Hhour of day (0~23)number0
kclockhour of day (1~24)number24
mminute of hournumber30
ssecond of minutenumber55
Sfraction of secondmillis978
ztime zonetextPacific Standard Time; PST
Ztime zone offset/idzone-0800; -08:00; America/Los_Angeles
'escape for textdelimiter''

Time zone

POST /sales/_search?size=0
{
"aggs": {
"range": {
"date_range": {
"field": "date",
"time_zone": "CET",
"ranges": [
{ "to": "2016/02/01" },
{ "from": "2016/02/01", "to" : "now/d" },
{ "from": "now/d" }
]
}
}
}
}

Keyed Response

将keyed标志设置为true会将一个唯一的字符串键与每个bucket相关联,并将范围作为哈希而不是数组返回:

POST /sales/_search?size=0
{
"aggs": {
"range": {
"date_range": {
"field": "date",
"format": "MM-yyy",
"ranges": [
{ "to": "now-10M/M" },
{ "from": "now-10M/M" }
],
"keyed": true
}
}
}
}

返回

{
...
"aggregations": {
"range": {
"buckets": {
"*-10-2015": {
"to": 1.4436576E12,
"to_as_string": "10-2015",
"doc_count": 7
},
"10-2015-*": {
"from": 1.4436576E12,
"from_as_string": "10-2015",
"doc_count": 0
}
}
}
}
}

还可以自定义每个范围的key:

POST /sales/_search?size=0
{
"aggs": {
"range": {
"date_range": {
"field": "date",
"format": "MM-yyy",
"ranges": [
{ "from": "01-2015", "to": "03-2015", "key": "quarter_01" },
{ "from": "03-2015", "to": "06-2015", "key": "quarter_02" }
],
"keyed": true
}
}
}
}

返回

{
...
"aggregations": {
"range": {
"buckets": {
"quarter_01": {
"from": 1.4200704E12,
"from_as_string": "01-2015",
"to": 1.425168E12,
"to_as_string": "03-2015",
"doc_count": 5
},
"quarter_02": {
"from": 1.425168E12,
"from_as_string": "03-2015",
"to": 1.4331168E12,
"to_as_string": "06-2015",
"doc_count": 2
}
}
}
}
}