movfn-aggregation.asciidoc 21 KB

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