datehistogram-aggregation.asciidoc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. [[search-aggregations-bucket-datehistogram-aggregation]]
  2. === Date Histogram Aggregation
  3. This multi-bucket aggregation is similar to the normal
  4. <<search-aggregations-bucket-histogram-aggregation,histogram>>, but it can
  5. only be used with date values. Because dates are represented internally in
  6. Elasticsearch as long values, it is possible, but not as accurate, to use the
  7. normal `histogram` on dates as well. The main difference in the two APIs is
  8. that here the interval can be specified using date/time expressions. Time-based
  9. data requires special support because time-based intervals are not always a
  10. fixed length.
  11. ==== Calendar and Fixed intervals
  12. When configuring a date histogram aggregation, the interval can be specified
  13. in two manners: calendar-aware time intervals, and fixed time intervals.
  14. Calendar-aware intervals understand that daylight savings changes the length
  15. of specific days, months have different amounts of days, and leap seconds can
  16. be tacked onto a particular year.
  17. Fixed intervals are, by contrast, always multiples of SI units and do not change
  18. based on calendaring context.
  19. [NOTE]
  20. .Combined `interval` field is deprecated
  21. ==================================
  22. deprecated[7.2, `interval` field is deprecated] Historically both calendar and fixed
  23. intervals were configured in a single `interval` field, which led to confusing
  24. semantics. Specifying `1d` would be assumed as a calendar-aware time,
  25. whereas `2d` would be interpreted as fixed time. To get "one day" of fixed time,
  26. the user would need to specify the next smaller unit (in this case, `24h`).
  27. This combined behavior was often unknown to users, and even when knowledgeable about
  28. the behavior it was difficult to use and confusing.
  29. This behavior has been deprecated in favor of two new, explicit fields: `calendar_interval`
  30. and `fixed_interval`.
  31. By forcing a choice between calendar and intervals up front, the semantics of the interval
  32. are clear to the user immediately and there is no ambiguity. The old `interval` field
  33. will be removed in the future.
  34. ==================================
  35. ===== Calendar Intervals
  36. Calendar-aware intervals are configured with the `calendar_interval` parameter.
  37. Calendar intervals can only be specified in "singular" quantities of the unit
  38. (`1d`, `1M`, etc). Multiples, such as `2d`, are not supported and will throw an exception.
  39. The accepted units for calendar intervals are:
  40. minute (`m`, `1m`) ::
  41. All minutes begin at 00 seconds.
  42. One minute is the interval between 00 seconds of the first minute and 00
  43. seconds of the following minute in the specified timezone, compensating for any
  44. intervening leap seconds, so that the number of minutes and seconds past the
  45. hour is the same at the start and end.
  46. hours (`h`, `1h`) ::
  47. All hours begin at 00 minutes and 00 seconds.
  48. One hour (1h) is the interval between 00:00 minutes of the first hour and 00:00
  49. minutes of the following hour in the specified timezone, compensating for any
  50. intervening leap seconds, so that the number of minutes and seconds past the hour
  51. is the same at the start and end.
  52. days (`d`, `1d`) ::
  53. All days begin at the earliest possible time, which is usually 00:00:00
  54. (midnight).
  55. One day (1d) is the interval between the start of the day and the start of
  56. of the following day in the specified timezone, compensating for any intervening
  57. time changes.
  58. week (`w`, `1w`) ::
  59. One week is the interval between the start day_of_week:hour:minute:second
  60. and the same day of the week and time of the following week in the specified
  61. timezone.
  62. month (`M`, `1M`) ::
  63. One month is the interval between the start day of the month and time of
  64. day and the same day of the month and time of the following month in the specified
  65. timezone, so that the day of the month and time of day are the same at the start
  66. and end.
  67. quarter (`q`, `1q`) ::
  68. One quarter (1q) is the interval between the start day of the month and
  69. time of day and the same day of the month and time of day three months later,
  70. so that the day of the month and time of day are the same at the start and end. +
  71. year (`y`, `1y`) ::
  72. One year (1y) is the interval between the start day of the month and time of
  73. day and the same day of the month and time of day the following year in the
  74. specified timezone, so that the date and time are the same at the start and end. +
  75. ===== Calendar Interval Examples
  76. As an example, here is an aggregation requesting bucket intervals of a month in calendar time:
  77. [source,console]
  78. --------------------------------------------------
  79. POST /sales/_search?size=0
  80. {
  81. "aggs" : {
  82. "sales_over_time" : {
  83. "date_histogram" : {
  84. "field" : "date",
  85. "calendar_interval" : "month"
  86. }
  87. }
  88. }
  89. }
  90. --------------------------------------------------
  91. // TEST[setup:sales]
  92. If you attempt to use multiples of calendar units, the aggregation will fail because only
  93. singular calendar units are supported:
  94. [source,console]
  95. --------------------------------------------------
  96. POST /sales/_search?size=0
  97. {
  98. "aggs" : {
  99. "sales_over_time" : {
  100. "date_histogram" : {
  101. "field" : "date",
  102. "calendar_interval" : "2d"
  103. }
  104. }
  105. }
  106. }
  107. --------------------------------------------------
  108. // TEST[setup:sales]
  109. // TEST[catch:bad_request]
  110. [source,js]
  111. --------------------------------------------------
  112. {
  113. "error" : {
  114. "root_cause" : [...],
  115. "type" : "x_content_parse_exception",
  116. "reason" : "[1:82] [date_histogram] failed to parse field [calendar_interval]",
  117. "caused_by" : {
  118. "type" : "illegal_argument_exception",
  119. "reason" : "The supplied interval [2d] could not be parsed as a calendar interval.",
  120. "stack_trace" : "java.lang.IllegalArgumentException: The supplied interval [2d] could not be parsed as a calendar interval."
  121. }
  122. }
  123. }
  124. --------------------------------------------------
  125. // NOTCONSOLE
  126. ===== Fixed Intervals
  127. Fixed intervals are configured with the `fixed_interval` parameter.
  128. In contrast to calendar-aware intervals, fixed intervals are a fixed number of SI
  129. units and never deviate, regardless of where they fall on the calendar. One second
  130. is always composed of 1000ms. This allows fixed intervals to be specified in
  131. any multiple of the supported units.
  132. However, it means fixed intervals cannot express other units such as months,
  133. since the duration of a month is not a fixed quantity. Attempting to specify
  134. a calendar interval like month or quarter will throw an exception.
  135. The accepted units for fixed intervals are:
  136. milliseconds (ms) ::
  137. seconds (s) ::
  138. Defined as 1000 milliseconds each
  139. minutes (m) ::
  140. All minutes begin at 00 seconds.
  141. Defined as 60 seconds each (60,000 milliseconds)
  142. hours (h) ::
  143. All hours begin at 00 minutes and 00 seconds.
  144. Defined as 60 minutes each (3,600,000 milliseconds)
  145. days (d) ::
  146. All days begin at the earliest possible time, which is usually 00:00:00
  147. (midnight).
  148. Defined as 24 hours (86,400,000 milliseconds)
  149. ===== Fixed Interval Examples
  150. If we try to recreate the "month" `calendar_interval` from earlier, we can approximate that with
  151. 30 fixed days:
  152. [source,console]
  153. --------------------------------------------------
  154. POST /sales/_search?size=0
  155. {
  156. "aggs" : {
  157. "sales_over_time" : {
  158. "date_histogram" : {
  159. "field" : "date",
  160. "fixed_interval" : "30d"
  161. }
  162. }
  163. }
  164. }
  165. --------------------------------------------------
  166. // TEST[setup:sales]
  167. But if we try to use a calendar unit that is not supported, such as weeks, we'll get an exception:
  168. [source,console]
  169. --------------------------------------------------
  170. POST /sales/_search?size=0
  171. {
  172. "aggs" : {
  173. "sales_over_time" : {
  174. "date_histogram" : {
  175. "field" : "date",
  176. "fixed_interval" : "2w"
  177. }
  178. }
  179. }
  180. }
  181. --------------------------------------------------
  182. // TEST[setup:sales]
  183. // TEST[catch:bad_request]
  184. [source,js]
  185. --------------------------------------------------
  186. {
  187. "error" : {
  188. "root_cause" : [...],
  189. "type" : "x_content_parse_exception",
  190. "reason" : "[1:82] [date_histogram] failed to parse field [fixed_interval]",
  191. "caused_by" : {
  192. "type" : "illegal_argument_exception",
  193. "reason" : "failed to parse setting [date_histogram.fixedInterval] with value [2w] as a time value: unit is missing or unrecognized",
  194. "stack_trace" : "java.lang.IllegalArgumentException: failed to parse setting [date_histogram.fixedInterval] with value [2w] as a time value: unit is missing or unrecognized"
  195. }
  196. }
  197. }
  198. --------------------------------------------------
  199. // NOTCONSOLE
  200. ===== Notes
  201. In all cases, when the specified end time does not exist, the actual end time is
  202. the closest available time after the specified end.
  203. Widely distributed applications must also consider vagaries such as countries that
  204. start and stop daylight savings time at 12:01 A.M., so end up with one minute of
  205. Sunday followed by an additional 59 minutes of Saturday once a year, and countries
  206. that decide to move across the international date line. Situations like
  207. that can make irregular timezone offsets seem easy.
  208. As always, rigorous testing, especially around time-change events, will ensure
  209. that your time interval specification is
  210. what you intend it to be.
  211. WARNING:
  212. To avoid unexpected results, all connected servers and clients must sync to a
  213. reliable network time service.
  214. NOTE: fractional time values are not supported, but you can address this by
  215. shifting to another time unit (e.g., `1.5h` could instead be specified as `90m`).
  216. NOTE: You can also specify time values using abbreviations supported by
  217. <<time-units,time units>> parsing.
  218. ===== Keys
  219. Internally, a date is represented as a 64 bit number representing a timestamp
  220. in milliseconds-since-the-epoch (01/01/1970 midnight UTC). These timestamps are
  221. returned as the ++key++ name of the bucket. The `key_as_string` is the same
  222. timestamp converted to a formatted
  223. date string using the `format` parameter specification:
  224. TIP: If you don't specify `format`, the first date
  225. <<mapping-date-format,format>> specified in the field mapping is used.
  226. [source,console]
  227. --------------------------------------------------
  228. POST /sales/_search?size=0
  229. {
  230. "aggs" : {
  231. "sales_over_time" : {
  232. "date_histogram" : {
  233. "field" : "date",
  234. "calendar_interval" : "1M",
  235. "format" : "yyyy-MM-dd" <1>
  236. }
  237. }
  238. }
  239. }
  240. --------------------------------------------------
  241. // TEST[setup:sales]
  242. <1> Supports expressive date <<date-format-pattern,format pattern>>
  243. Response:
  244. [source,js]
  245. --------------------------------------------------
  246. {
  247. ...
  248. "aggregations": {
  249. "sales_over_time": {
  250. "buckets": [
  251. {
  252. "key_as_string": "2015-01-01",
  253. "key": 1420070400000,
  254. "doc_count": 3
  255. },
  256. {
  257. "key_as_string": "2015-02-01",
  258. "key": 1422748800000,
  259. "doc_count": 2
  260. },
  261. {
  262. "key_as_string": "2015-03-01",
  263. "key": 1425168000000,
  264. "doc_count": 2
  265. }
  266. ]
  267. }
  268. }
  269. }
  270. --------------------------------------------------
  271. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  272. ===== Timezone
  273. Date-times are stored in Elasticsearch in UTC. By default, all bucketing and
  274. rounding is also done in UTC. Use the `time_zone` parameter to indicate
  275. that bucketing should use a different timezone.
  276. You can specify timezones as either an ISO 8601 UTC offset (e.g. `+01:00` or
  277. `-08:00`) or as a timezone ID as specified in the IANA timezone database,
  278. such as`America/Los_Angeles`.
  279. Consider the following example:
  280. [source,console]
  281. ---------------------------------
  282. PUT my_index/_doc/1?refresh
  283. {
  284. "date": "2015-10-01T00:30:00Z"
  285. }
  286. PUT my_index/_doc/2?refresh
  287. {
  288. "date": "2015-10-01T01:30:00Z"
  289. }
  290. GET my_index/_search?size=0
  291. {
  292. "aggs": {
  293. "by_day": {
  294. "date_histogram": {
  295. "field": "date",
  296. "calendar_interval": "day"
  297. }
  298. }
  299. }
  300. }
  301. ---------------------------------
  302. If you don't specify a timezone, UTC is used. This would result in both of these
  303. documents being placed into the same day bucket, which starts at midnight UTC
  304. on 1 October 2015:
  305. [source,js]
  306. ---------------------------------
  307. {
  308. ...
  309. "aggregations": {
  310. "by_day": {
  311. "buckets": [
  312. {
  313. "key_as_string": "2015-10-01T00:00:00.000Z",
  314. "key": 1443657600000,
  315. "doc_count": 2
  316. }
  317. ]
  318. }
  319. }
  320. }
  321. ---------------------------------
  322. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  323. If you specify a `time_zone` of `-01:00`, midnight in that timezone is one hour
  324. before midnight UTC:
  325. [source,console]
  326. ---------------------------------
  327. GET my_index/_search?size=0
  328. {
  329. "aggs": {
  330. "by_day": {
  331. "date_histogram": {
  332. "field": "date",
  333. "calendar_interval": "day",
  334. "time_zone": "-01:00"
  335. }
  336. }
  337. }
  338. }
  339. ---------------------------------
  340. // TEST[continued]
  341. Now the first document falls into the bucket for 30 September 2015, while the
  342. second document falls into the bucket for 1 October 2015:
  343. [source,js]
  344. ---------------------------------
  345. {
  346. ...
  347. "aggregations": {
  348. "by_day": {
  349. "buckets": [
  350. {
  351. "key_as_string": "2015-09-30T00:00:00.000-01:00", <1>
  352. "key": 1443574800000,
  353. "doc_count": 1
  354. },
  355. {
  356. "key_as_string": "2015-10-01T00:00:00.000-01:00", <1>
  357. "key": 1443661200000,
  358. "doc_count": 1
  359. }
  360. ]
  361. }
  362. }
  363. }
  364. ---------------------------------
  365. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  366. <1> The `key_as_string` value represents midnight on each day
  367. in the specified timezone.
  368. WARNING: When using time zones that follow DST (daylight savings time) changes,
  369. buckets close to the moment when those changes happen can have slightly different
  370. sizes than you would expect from the used `interval`.
  371. For example, consider a DST start in the `CET` time zone: on 27 March 2016 at 2am,
  372. clocks were turned forward 1 hour to 3am local time. If you use `day` as `interval`,
  373. the bucket covering that day will only hold data for 23 hours instead of the usual
  374. 24 hours for other buckets. The same is true for shorter intervals, like 12h,
  375. where you'll have only a 11h bucket on the morning of 27 March when the DST shift
  376. happens.
  377. ===== Offset
  378. Use the `offset` parameter to change the start value of each bucket by the
  379. specified positive (`+`) or negative offset (`-`) duration, such as `1h` for
  380. an hour, or `1d` for a day. See <<time-units>> for more possible time
  381. duration options.
  382. For example, when using an interval of `day`, each bucket runs from midnight
  383. to midnight. Setting the `offset` parameter to `+6h` changes each bucket
  384. to run from 6am to 6am:
  385. [source,console]
  386. -----------------------------
  387. PUT my_index/_doc/1?refresh
  388. {
  389. "date": "2015-10-01T05:30:00Z"
  390. }
  391. PUT my_index/_doc/2?refresh
  392. {
  393. "date": "2015-10-01T06:30:00Z"
  394. }
  395. GET my_index/_search?size=0
  396. {
  397. "aggs": {
  398. "by_day": {
  399. "date_histogram": {
  400. "field": "date",
  401. "calendar_interval": "day",
  402. "offset": "+6h"
  403. }
  404. }
  405. }
  406. }
  407. -----------------------------
  408. Instead of a single bucket starting at midnight, the above request groups the
  409. documents into buckets starting at 6am:
  410. [source,js]
  411. -----------------------------
  412. {
  413. ...
  414. "aggregations": {
  415. "by_day": {
  416. "buckets": [
  417. {
  418. "key_as_string": "2015-09-30T06:00:00.000Z",
  419. "key": 1443592800000,
  420. "doc_count": 1
  421. },
  422. {
  423. "key_as_string": "2015-10-01T06:00:00.000Z",
  424. "key": 1443679200000,
  425. "doc_count": 1
  426. }
  427. ]
  428. }
  429. }
  430. }
  431. -----------------------------
  432. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  433. NOTE: The start `offset` of each bucket is calculated after `time_zone`
  434. adjustments have been made.
  435. ===== Keyed Response
  436. Setting the `keyed` flag to `true` associates a unique string key with each
  437. bucket and returns the ranges as a hash rather than an array:
  438. [source,console]
  439. --------------------------------------------------
  440. POST /sales/_search?size=0
  441. {
  442. "aggs" : {
  443. "sales_over_time" : {
  444. "date_histogram" : {
  445. "field" : "date",
  446. "calendar_interval" : "1M",
  447. "format" : "yyyy-MM-dd",
  448. "keyed": true
  449. }
  450. }
  451. }
  452. }
  453. --------------------------------------------------
  454. // TEST[setup:sales]
  455. Response:
  456. [source,js]
  457. --------------------------------------------------
  458. {
  459. ...
  460. "aggregations": {
  461. "sales_over_time": {
  462. "buckets": {
  463. "2015-01-01": {
  464. "key_as_string": "2015-01-01",
  465. "key": 1420070400000,
  466. "doc_count": 3
  467. },
  468. "2015-02-01": {
  469. "key_as_string": "2015-02-01",
  470. "key": 1422748800000,
  471. "doc_count": 2
  472. },
  473. "2015-03-01": {
  474. "key_as_string": "2015-03-01",
  475. "key": 1425168000000,
  476. "doc_count": 2
  477. }
  478. }
  479. }
  480. }
  481. }
  482. --------------------------------------------------
  483. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  484. ===== Scripts
  485. As with the normal <<search-aggregations-bucket-histogram-aggregation,histogram>>,
  486. both document-level scripts and
  487. value-level scripts are supported. You can control the order of the returned
  488. buckets using the `order`
  489. settings and filter the returned buckets based on a `min_doc_count` setting
  490. (by default all buckets between the first
  491. bucket that matches documents and the last one are returned). This histogram
  492. also supports the `extended_bounds`
  493. setting, which enables extending the bounds of the histogram beyond the data
  494. itself. For more information, see
  495. <<search-aggregations-bucket-histogram-aggregation-extended-bounds,`Extended Bounds`>>.
  496. ===== Missing value
  497. The `missing` parameter defines how to treat documents that are missing a value.
  498. By default, they are ignored, but it is also possible to treat them as if they
  499. have a value.
  500. [source,console]
  501. --------------------------------------------------
  502. POST /sales/_search?size=0
  503. {
  504. "aggs" : {
  505. "sale_date" : {
  506. "date_histogram" : {
  507. "field" : "date",
  508. "calendar_interval": "year",
  509. "missing": "2000/01/01" <1>
  510. }
  511. }
  512. }
  513. }
  514. --------------------------------------------------
  515. // TEST[setup:sales]
  516. <1> Documents without a value in the `publish_date` field will fall into the
  517. same bucket as documents that have the value `2000-01-01`.
  518. ===== Order
  519. By default the returned buckets are sorted by their `key` ascending, but you can
  520. control the order using
  521. the `order` setting. This setting supports the same `order` functionality as
  522. <<search-aggregations-bucket-terms-aggregation-order,`Terms Aggregation`>>.
  523. ===== Using a script to aggregate by day of the week
  524. When you need to aggregate the results by day of the week, use a script that
  525. returns the day of the week:
  526. [source,console]
  527. --------------------------------------------------
  528. POST /sales/_search?size=0
  529. {
  530. "aggs": {
  531. "dayOfWeek": {
  532. "terms": {
  533. "script": {
  534. "lang": "painless",
  535. "source": "doc['date'].value.dayOfWeekEnum.value"
  536. }
  537. }
  538. }
  539. }
  540. }
  541. --------------------------------------------------
  542. // TEST[setup:sales]
  543. Response:
  544. [source,js]
  545. --------------------------------------------------
  546. {
  547. ...
  548. "aggregations": {
  549. "dayOfWeek": {
  550. "doc_count_error_upper_bound": 0,
  551. "sum_other_doc_count": 0,
  552. "buckets": [
  553. {
  554. "key": "7",
  555. "doc_count": 4
  556. },
  557. {
  558. "key": "4",
  559. "doc_count": 3
  560. }
  561. ]
  562. }
  563. }
  564. }
  565. --------------------------------------------------
  566. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  567. The response will contain all the buckets having the relative day of
  568. the week as key : 1 for Monday, 2 for Tuesday... 7 for Sunday.