datehistogram-aggregation.asciidoc 20 KB

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