movfn-aggregation.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. [[search-aggregations-pipeline-movfn-aggregation]]
  2. === Moving function aggregation
  3. ++++
  4. <titleabbrev>Moving function</titleabbrev>
  5. ++++
  6. Given an ordered series of data, the Moving Function aggregation will slide a window across the data and allow the user to specify a custom
  7. script that is executed on each window of data. For convenience, a number of common functions are predefined such as min/max, moving averages,
  8. etc.
  9. ==== Syntax
  10. A `moving_fn` aggregation looks like this in isolation:
  11. [source,js]
  12. --------------------------------------------------
  13. {
  14. "moving_fn": {
  15. "buckets_path": "the_sum",
  16. "window": 10,
  17. "script": "MovingFunctions.min(values)"
  18. }
  19. }
  20. --------------------------------------------------
  21. // NOTCONSOLE
  22. [[moving-fn-params]]
  23. .`moving_fn` Parameters
  24. [options="header"]
  25. |===
  26. |Parameter Name |Description |Required |Default Value
  27. |`buckets_path` |Path to the metric of interest (see <<buckets-path-syntax, `buckets_path` Syntax>> for more details |Required |
  28. |`window` |The size of window to "slide" across the histogram. |Required |
  29. |`script` |The script that should be executed on each window of data |Required |
  30. |`gap_policy` |The policy to apply when gaps are found in the data. See <<gap-policy>>. |Optional |`skip`
  31. |`shift` |<<shift-parameter, Shift>> of window position. |Optional | 0
  32. |===
  33. `moving_fn` aggregations must be embedded inside of a `histogram` or `date_histogram` aggregation. They can be
  34. embedded like any other metric aggregation:
  35. [source,console]
  36. --------------------------------------------------
  37. POST /_search
  38. {
  39. "size": 0,
  40. "aggs": {
  41. "my_date_histo": { <1>
  42. "date_histogram": {
  43. "field": "date",
  44. "calendar_interval": "1M"
  45. },
  46. "aggs": {
  47. "the_sum": {
  48. "sum": { "field": "price" } <2>
  49. },
  50. "the_movfn": {
  51. "moving_fn": {
  52. "buckets_path": "the_sum", <3>
  53. "window": 10,
  54. "script": "MovingFunctions.unweightedAvg(values)"
  55. }
  56. }
  57. }
  58. }
  59. }
  60. }
  61. --------------------------------------------------
  62. // TEST[setup:sales]
  63. <1> A `date_histogram` named "my_date_histo" is constructed on the "timestamp" field, with one-day intervals
  64. <2> A `sum` metric is used to calculate the sum of a field. This could be any numeric metric (sum, min, max, etc)
  65. <3> Finally, we specify a `moving_fn` aggregation which uses "the_sum" metric as its input.
  66. Moving averages are built by first specifying a `histogram` or `date_histogram` over a field. You can then optionally
  67. add numeric metrics, such as a `sum`, inside of that histogram. Finally, the `moving_fn` is embedded inside the histogram.
  68. The `buckets_path` parameter is then used to "point" at one of the sibling metrics inside of the histogram (see
  69. <<buckets-path-syntax>> for a description of the syntax for `buckets_path`.
  70. An example response from the above aggregation may look like:
  71. [source,console-result]
  72. --------------------------------------------------
  73. {
  74. "took": 11,
  75. "timed_out": false,
  76. "_shards": ...,
  77. "hits": ...,
  78. "aggregations": {
  79. "my_date_histo": {
  80. "buckets": [
  81. {
  82. "key_as_string": "2015/01/01 00:00:00",
  83. "key": 1420070400000,
  84. "doc_count": 3,
  85. "the_sum": {
  86. "value": 550.0
  87. },
  88. "the_movfn": {
  89. "value": null
  90. }
  91. },
  92. {
  93. "key_as_string": "2015/02/01 00:00:00",
  94. "key": 1422748800000,
  95. "doc_count": 2,
  96. "the_sum": {
  97. "value": 60.0
  98. },
  99. "the_movfn": {
  100. "value": 550.0
  101. }
  102. },
  103. {
  104. "key_as_string": "2015/03/01 00:00:00",
  105. "key": 1425168000000,
  106. "doc_count": 2,
  107. "the_sum": {
  108. "value": 375.0
  109. },
  110. "the_movfn": {
  111. "value": 305.0
  112. }
  113. }
  114. ]
  115. }
  116. }
  117. }
  118. --------------------------------------------------
  119. // TESTRESPONSE[s/"took": 11/"took": $body.took/]
  120. // TESTRESPONSE[s/"_shards": \.\.\./"_shards": $body._shards/]
  121. // TESTRESPONSE[s/"hits": \.\.\./"hits": $body.hits/]
  122. ==== Custom user scripting
  123. The Moving Function aggregation allows the user to specify any arbitrary script to define custom logic. The script is invoked each time a
  124. new window of data is collected. These values are provided to the script in the `values` variable. The script should then perform some
  125. kind of calculation and emit a single `double` as the result. Emitting `null` is not permitted, although `NaN` and +/- `Inf` are allowed.
  126. For example, this script will simply return the first value from the window, or `NaN` if no values are available:
  127. [source,console]
  128. --------------------------------------------------
  129. POST /_search
  130. {
  131. "size": 0,
  132. "aggs": {
  133. "my_date_histo": {
  134. "date_histogram": {
  135. "field": "date",
  136. "calendar_interval": "1M"
  137. },
  138. "aggs": {
  139. "the_sum": {
  140. "sum": { "field": "price" }
  141. },
  142. "the_movavg": {
  143. "moving_fn": {
  144. "buckets_path": "the_sum",
  145. "window": 10,
  146. "script": "return values.length > 0 ? values[0] : Double.NaN"
  147. }
  148. }
  149. }
  150. }
  151. }
  152. }
  153. --------------------------------------------------
  154. // TEST[setup:sales]
  155. [[shift-parameter]]
  156. ==== shift parameter
  157. By default (with `shift = 0`), the window that is offered for calculation is the last `n` values excluding the current bucket.
  158. Increasing `shift` by 1 moves starting window position by `1` to the right.
  159. - To include current bucket to the window, use `shift = 1`.
  160. - For center alignment (`n / 2` values before and after the current bucket), use `shift = window / 2`.
  161. - For right alignment (`n` values after the current bucket), use `shift = window`.
  162. If either of window edges moves outside the borders of data series, the window shrinks to include available values only.
  163. ==== Pre-built Functions
  164. For convenience, a number of functions have been prebuilt and are available inside the `moving_fn` script context:
  165. - `max()`
  166. - `min()`
  167. - `sum()`
  168. - `stdDev()`
  169. - `unweightedAvg()`
  170. - `linearWeightedAvg()`
  171. - `ewma()`
  172. - `holt()`
  173. - `holtWinters()`
  174. The functions are available from the `MovingFunctions` namespace. E.g. `MovingFunctions.max()`
  175. ===== max Function
  176. This function accepts a collection of doubles and returns the maximum value in that window. `null` and `NaN` values are ignored; the maximum
  177. is only calculated over the real values. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  178. [[max-params]]
  179. .`max(double[] values)` Parameters
  180. [options="header"]
  181. |===
  182. |Parameter Name |Description
  183. |`values` |The window of values to find the maximum
  184. |===
  185. [source,console]
  186. --------------------------------------------------
  187. POST /_search
  188. {
  189. "size": 0,
  190. "aggs": {
  191. "my_date_histo": {
  192. "date_histogram": {
  193. "field": "date",
  194. "calendar_interval": "1M"
  195. },
  196. "aggs": {
  197. "the_sum": {
  198. "sum": { "field": "price" }
  199. },
  200. "the_moving_max": {
  201. "moving_fn": {
  202. "buckets_path": "the_sum",
  203. "window": 10,
  204. "script": "MovingFunctions.max(values)"
  205. }
  206. }
  207. }
  208. }
  209. }
  210. }
  211. --------------------------------------------------
  212. // TEST[setup:sales]
  213. ===== min Function
  214. This function accepts a collection of doubles and returns the minimum value in that window. `null` and `NaN` values are ignored; the minimum
  215. is only calculated over the real values. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  216. [[min-params]]
  217. .`min(double[] values)` Parameters
  218. [options="header"]
  219. |===
  220. |Parameter Name |Description
  221. |`values` |The window of values to find the minimum
  222. |===
  223. [source,console]
  224. --------------------------------------------------
  225. POST /_search
  226. {
  227. "size": 0,
  228. "aggs": {
  229. "my_date_histo": {
  230. "date_histogram": {
  231. "field": "date",
  232. "calendar_interval": "1M"
  233. },
  234. "aggs": {
  235. "the_sum": {
  236. "sum": { "field": "price" }
  237. },
  238. "the_moving_min": {
  239. "moving_fn": {
  240. "buckets_path": "the_sum",
  241. "window": 10,
  242. "script": "MovingFunctions.min(values)"
  243. }
  244. }
  245. }
  246. }
  247. }
  248. }
  249. --------------------------------------------------
  250. // TEST[setup:sales]
  251. ===== sum Function
  252. This function accepts a collection of doubles and returns the sum of the values in that window. `null` and `NaN` values are ignored;
  253. the sum is only calculated over the real values. If the window is empty, or all values are `null`/`NaN`, `0.0` is returned as the result.
  254. [[sum-params]]
  255. .`sum(double[] values)` Parameters
  256. [options="header"]
  257. |===
  258. |Parameter Name |Description
  259. |`values` |The window of values to find the sum of
  260. |===
  261. [source,console]
  262. --------------------------------------------------
  263. POST /_search
  264. {
  265. "size": 0,
  266. "aggs": {
  267. "my_date_histo": {
  268. "date_histogram": {
  269. "field": "date",
  270. "calendar_interval": "1M"
  271. },
  272. "aggs": {
  273. "the_sum": {
  274. "sum": { "field": "price" }
  275. },
  276. "the_moving_sum": {
  277. "moving_fn": {
  278. "buckets_path": "the_sum",
  279. "window": 10,
  280. "script": "MovingFunctions.sum(values)"
  281. }
  282. }
  283. }
  284. }
  285. }
  286. }
  287. --------------------------------------------------
  288. // TEST[setup:sales]
  289. ===== stdDev Function
  290. This function accepts a collection of doubles and average, then returns the standard deviation of the values in that window.
  291. `null` and `NaN` values are ignored; the sum is only calculated over the real values. If the window is empty, or all values are
  292. `null`/`NaN`, `0.0` is returned as the result.
  293. [[stddev-params]]
  294. .`stdDev(double[] values)` Parameters
  295. [options="header"]
  296. |===
  297. |Parameter Name |Description
  298. |`values` |The window of values to find the standard deviation of
  299. |`avg` |The average of the window
  300. |===
  301. [source,console]
  302. --------------------------------------------------
  303. POST /_search
  304. {
  305. "size": 0,
  306. "aggs": {
  307. "my_date_histo": {
  308. "date_histogram": {
  309. "field": "date",
  310. "calendar_interval": "1M"
  311. },
  312. "aggs": {
  313. "the_sum": {
  314. "sum": { "field": "price" }
  315. },
  316. "the_moving_sum": {
  317. "moving_fn": {
  318. "buckets_path": "the_sum",
  319. "window": 10,
  320. "script": "MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))"
  321. }
  322. }
  323. }
  324. }
  325. }
  326. }
  327. --------------------------------------------------
  328. // TEST[setup:sales]
  329. The `avg` parameter must be provided to the standard deviation function because different styles of averages can be computed on the window
  330. (simple, linearly weighted, etc). The various moving averages that are detailed below can be used to calculate the average for the
  331. standard deviation function.
  332. ===== unweightedAvg Function
  333. The `unweightedAvg` function calculates the sum of all values in the window, then divides by the size of the window. It is effectively
  334. a simple arithmetic mean of the window. The simple moving average does not perform any time-dependent weighting, which means
  335. the values from a `simple` moving average tend to "lag" behind the real data.
  336. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  337. `null`/`NaN`, `NaN` is returned as the result. This means that the count used in the average calculation is count of non-`null`,non-`NaN`
  338. values.
  339. [[unweightedavg-params]]
  340. .`unweightedAvg(double[] values)` Parameters
  341. [options="header"]
  342. |===
  343. |Parameter Name |Description
  344. |`values` |The window of values to find the sum of
  345. |===
  346. [source,console]
  347. --------------------------------------------------
  348. POST /_search
  349. {
  350. "size": 0,
  351. "aggs": {
  352. "my_date_histo": {
  353. "date_histogram": {
  354. "field": "date",
  355. "calendar_interval": "1M"
  356. },
  357. "aggs": {
  358. "the_sum": {
  359. "sum": { "field": "price" }
  360. },
  361. "the_movavg": {
  362. "moving_fn": {
  363. "buckets_path": "the_sum",
  364. "window": 10,
  365. "script": "MovingFunctions.unweightedAvg(values)"
  366. }
  367. }
  368. }
  369. }
  370. }
  371. }
  372. --------------------------------------------------
  373. // TEST[setup:sales]
  374. ==== linearWeightedAvg Function
  375. The `linearWeightedAvg` function assigns a linear weighting to points in the series, such that "older" datapoints (e.g. those at
  376. the beginning of the window) contribute a linearly less amount to the total average. The linear weighting helps reduce
  377. the "lag" behind the data's mean, since older points have less influence.
  378. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  379. [[linearweightedavg-params]]
  380. .`linearWeightedAvg(double[] values)` Parameters
  381. [options="header"]
  382. |===
  383. |Parameter Name |Description
  384. |`values` |The window of values to find the sum of
  385. |===
  386. [source,console]
  387. --------------------------------------------------
  388. POST /_search
  389. {
  390. "size": 0,
  391. "aggs": {
  392. "my_date_histo": {
  393. "date_histogram": {
  394. "field": "date",
  395. "calendar_interval": "1M"
  396. },
  397. "aggs": {
  398. "the_sum": {
  399. "sum": { "field": "price" }
  400. },
  401. "the_movavg": {
  402. "moving_fn": {
  403. "buckets_path": "the_sum",
  404. "window": 10,
  405. "script": "MovingFunctions.linearWeightedAvg(values)"
  406. }
  407. }
  408. }
  409. }
  410. }
  411. }
  412. --------------------------------------------------
  413. // TEST[setup:sales]
  414. ==== ewma Function
  415. The `ewma` function (aka "single-exponential") is similar to the `linearMovAvg` function,
  416. except older data-points become exponentially less important,
  417. rather than linearly less important. The speed at which the importance decays can be controlled with an `alpha`
  418. setting. Small values make the weight decay slowly, which provides greater smoothing and takes into account a larger
  419. portion of the window. Larger values make the weight decay quickly, which reduces the impact of older values on the
  420. moving average. This tends to make the moving average track the data more closely but with less smoothing.
  421. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  422. `null`/`NaN`, `NaN` is returned as the result. This means that the count used in the average calculation is count of non-`null`,non-`NaN`
  423. values.
  424. [[ewma-params]]
  425. .`ewma(double[] values, double alpha)` Parameters
  426. [options="header"]
  427. |===
  428. |Parameter Name |Description
  429. |`values` |The window of values to find the sum of
  430. |`alpha` |Exponential decay
  431. |===
  432. [source,console]
  433. --------------------------------------------------
  434. POST /_search
  435. {
  436. "size": 0,
  437. "aggs": {
  438. "my_date_histo": {
  439. "date_histogram": {
  440. "field": "date",
  441. "calendar_interval": "1M"
  442. },
  443. "aggs": {
  444. "the_sum": {
  445. "sum": { "field": "price" }
  446. },
  447. "the_movavg": {
  448. "moving_fn": {
  449. "buckets_path": "the_sum",
  450. "window": 10,
  451. "script": "MovingFunctions.ewma(values, 0.3)"
  452. }
  453. }
  454. }
  455. }
  456. }
  457. }
  458. --------------------------------------------------
  459. // TEST[setup:sales]
  460. ==== holt Function
  461. The `holt` function (aka "double exponential") incorporates a second exponential term which
  462. tracks the data's trend. Single exponential does not perform well when the data has an underlying linear trend. The
  463. double exponential model calculates two values internally: a "level" and a "trend".
  464. The level calculation is similar to `ewma`, and is an exponentially weighted view of the data. The difference is
  465. that the previously smoothed value is used instead of the raw value, which allows it to stay close to the original series.
  466. The trend calculation looks at the difference between the current and last value (e.g. the slope, or trend, of the
  467. smoothed data). The trend value is also exponentially weighted.
  468. Values are produced by multiplying the level and trend components.
  469. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  470. `null`/`NaN`, `NaN` is returned as the result. This means that the count used in the average calculation is count of non-`null`,non-`NaN`
  471. values.
  472. [[holt-params]]
  473. .`holt(double[] values, double alpha)` Parameters
  474. [options="header"]
  475. |===
  476. |Parameter Name |Description
  477. |`values` |The window of values to find the sum of
  478. |`alpha` |Level decay value
  479. |`beta` |Trend decay value
  480. |===
  481. [source,console]
  482. --------------------------------------------------
  483. POST /_search
  484. {
  485. "size": 0,
  486. "aggs": {
  487. "my_date_histo": {
  488. "date_histogram": {
  489. "field": "date",
  490. "calendar_interval": "1M"
  491. },
  492. "aggs": {
  493. "the_sum": {
  494. "sum": { "field": "price" }
  495. },
  496. "the_movavg": {
  497. "moving_fn": {
  498. "buckets_path": "the_sum",
  499. "window": 10,
  500. "script": "MovingFunctions.holt(values, 0.3, 0.1)"
  501. }
  502. }
  503. }
  504. }
  505. }
  506. }
  507. --------------------------------------------------
  508. // TEST[setup:sales]
  509. In practice, the `alpha` value behaves very similarly in `holtMovAvg` as `ewmaMovAvg`: small values produce more smoothing
  510. and more lag, while larger values produce closer tracking and less lag. The value of `beta` is often difficult
  511. to see. Small values emphasize long-term trends (such as a constant linear trend in the whole series), while larger
  512. values emphasize short-term trends.
  513. ==== holtWinters Function
  514. The `holtWinters` function (aka "triple exponential") incorporates a third exponential term which
  515. tracks the seasonal aspect of your data. This aggregation therefore smooths based on three components: "level", "trend"
  516. and "seasonality".
  517. The level and trend calculation is identical to `holt` The seasonal calculation looks at the difference between
  518. the current point, and the point one period earlier.
  519. Holt-Winters requires a little more handholding than the other moving averages. You need to specify the "periodicity"
  520. of your data: e.g. if your data has cyclic trends every 7 days, you would set `period = 7`. Similarly if there was
  521. a monthly trend, you would set it to `30`. There is currently no periodicity detection, although that is planned
  522. for future enhancements.
  523. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  524. `null`/`NaN`, `NaN` is returned as the result. This means that the count used in the average calculation is count of non-`null`,non-`NaN`
  525. values.
  526. [[holtwinters-params]]
  527. .`holtWinters(double[] values, double alpha)` Parameters
  528. [options="header"]
  529. |===
  530. |Parameter Name |Description
  531. |`values` |The window of values to find the sum of
  532. |`alpha` |Level decay value
  533. |`beta` |Trend decay value
  534. |`gamma` |Seasonality decay value
  535. |`period` |The periodicity of the data
  536. |`multiplicative` |True if you wish to use multiplicative holt-winters, false to use additive
  537. |===
  538. [source,console]
  539. --------------------------------------------------
  540. POST /_search
  541. {
  542. "size": 0,
  543. "aggs": {
  544. "my_date_histo": {
  545. "date_histogram": {
  546. "field": "date",
  547. "calendar_interval": "1M"
  548. },
  549. "aggs": {
  550. "the_sum": {
  551. "sum": { "field": "price" }
  552. },
  553. "the_movavg": {
  554. "moving_fn": {
  555. "buckets_path": "the_sum",
  556. "window": 10,
  557. "script": "if (values.length > 5*2) {MovingFunctions.holtWinters(values, 0.3, 0.1, 0.1, 5, false)}"
  558. }
  559. }
  560. }
  561. }
  562. }
  563. }
  564. --------------------------------------------------
  565. // TEST[setup:sales]
  566. [WARNING]
  567. ======
  568. Multiplicative Holt-Winters works by dividing each data point by the seasonal value. This is problematic if any of
  569. your data is zero, or if there are gaps in the data (since this results in a divid-by-zero). To combat this, the
  570. `mult` Holt-Winters pads all values by a very small amount (1*10^-10^) so that all values are non-zero. This affects
  571. the result, but only minimally. If your data is non-zero, or you prefer to see `NaN` when zero's are encountered,
  572. you can disable this behavior with `pad: false`
  573. ======
  574. ===== "Cold Start"
  575. Unfortunately, due to the nature of Holt-Winters, it requires two periods of data to "bootstrap" the algorithm. This
  576. means that your `window` must always be *at least* twice the size of your period. An exception will be thrown if it
  577. isn't. It also means that Holt-Winters will not emit a value for the first `2 * period` buckets; the current algorithm
  578. does not backcast.
  579. You'll notice in the above example we have an `if ()` statement checking the size of values. This is checking to make sure
  580. we have two periods worth of data (`5 * 2`, where 5 is the period specified in the `holtWintersMovAvg` function) before calling
  581. the holt-winters function.