movfn-aggregation.asciidoc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. |`shift` |<<shift-parameter, Shift>> of window position. |Optional | 0
  30. |===
  31. `moving_fn` aggregations must be embedded inside of a `histogram` or `date_histogram` aggregation. They can be
  32. embedded like any other metric aggregation:
  33. [source,js]
  34. --------------------------------------------------
  35. POST /_search
  36. {
  37. "size": 0,
  38. "aggs": {
  39. "my_date_histo":{ <1>
  40. "date_histogram":{
  41. "field":"date",
  42. "calendar_interval":"1M"
  43. },
  44. "aggs":{
  45. "the_sum":{
  46. "sum":{ "field": "price" } <2>
  47. },
  48. "the_movfn": {
  49. "moving_fn": {
  50. "buckets_path": "the_sum", <3>
  51. "window": 10,
  52. "script": "MovingFunctions.unweightedAvg(values)"
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }
  59. --------------------------------------------------
  60. // CONSOLE
  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,js]
  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,js]
  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. // CONSOLE
  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,js]
  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. // CONSOLE
  213. // TEST[setup:sales]
  214. ===== min Function
  215. This function accepts a collection of doubles and returns the minimum value in that window. `null` and `NaN` values are ignored; the minimum
  216. is only calculated over the real values. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  217. [[min-params]]
  218. .`min(double[] values)` Parameters
  219. [options="header"]
  220. |===
  221. |Parameter Name |Description
  222. |`values` |The window of values to find the minimum
  223. |===
  224. [source,js]
  225. --------------------------------------------------
  226. POST /_search
  227. {
  228. "size": 0,
  229. "aggs": {
  230. "my_date_histo":{
  231. "date_histogram":{
  232. "field":"date",
  233. "calendar_interval":"1M"
  234. },
  235. "aggs":{
  236. "the_sum":{
  237. "sum":{ "field": "price" }
  238. },
  239. "the_moving_min": {
  240. "moving_fn": {
  241. "buckets_path": "the_sum",
  242. "window": 10,
  243. "script": "MovingFunctions.min(values)"
  244. }
  245. }
  246. }
  247. }
  248. }
  249. }
  250. --------------------------------------------------
  251. // CONSOLE
  252. // TEST[setup:sales]
  253. ===== sum Function
  254. This function accepts a collection of doubles and returns the sum of the values in that window. `null` and `NaN` values are ignored;
  255. 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.
  256. [[sum-params]]
  257. .`sum(double[] values)` Parameters
  258. [options="header"]
  259. |===
  260. |Parameter Name |Description
  261. |`values` |The window of values to find the sum of
  262. |===
  263. [source,js]
  264. --------------------------------------------------
  265. POST /_search
  266. {
  267. "size": 0,
  268. "aggs": {
  269. "my_date_histo":{
  270. "date_histogram":{
  271. "field":"date",
  272. "calendar_interval":"1M"
  273. },
  274. "aggs":{
  275. "the_sum":{
  276. "sum":{ "field": "price" }
  277. },
  278. "the_moving_sum": {
  279. "moving_fn": {
  280. "buckets_path": "the_sum",
  281. "window": 10,
  282. "script": "MovingFunctions.sum(values)"
  283. }
  284. }
  285. }
  286. }
  287. }
  288. }
  289. --------------------------------------------------
  290. // CONSOLE
  291. // TEST[setup:sales]
  292. ===== stdDev Function
  293. This function accepts a collection of doubles and average, then returns the standard deviation of the values in that window.
  294. `null` and `NaN` values are ignored; the sum is only calculated over the real values. If the window is empty, or all values are
  295. `null`/`NaN`, `0.0` is returned as the result.
  296. [[stddev-params]]
  297. .`stdDev(double[] values)` Parameters
  298. [options="header"]
  299. |===
  300. |Parameter Name |Description
  301. |`values` |The window of values to find the standard deviation of
  302. |`avg` |The average of the window
  303. |===
  304. [source,js]
  305. --------------------------------------------------
  306. POST /_search
  307. {
  308. "size": 0,
  309. "aggs": {
  310. "my_date_histo":{
  311. "date_histogram":{
  312. "field":"date",
  313. "calendar_interval":"1M"
  314. },
  315. "aggs":{
  316. "the_sum":{
  317. "sum":{ "field": "price" }
  318. },
  319. "the_moving_sum": {
  320. "moving_fn": {
  321. "buckets_path": "the_sum",
  322. "window": 10,
  323. "script": "MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))"
  324. }
  325. }
  326. }
  327. }
  328. }
  329. }
  330. --------------------------------------------------
  331. // CONSOLE
  332. // TEST[setup:sales]
  333. The `avg` parameter must be provided to the standard deviation function because different styles of averages can be computed on the window
  334. (simple, linearly weighted, etc). The various moving averages that are detailed below can be used to calculate the average for the
  335. standard deviation function.
  336. ===== unweightedAvg Function
  337. The `unweightedAvg` function calculates the sum of all values in the window, then divides by the size of the window. It is effectively
  338. a simple arithmetic mean of the window. The simple moving average does not perform any time-dependent weighting, which means
  339. the values from a `simple` moving average tend to "lag" behind the real data.
  340. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  341. `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`
  342. values.
  343. [[unweightedavg-params]]
  344. .`unweightedAvg(double[] values)` Parameters
  345. [options="header"]
  346. |===
  347. |Parameter Name |Description
  348. |`values` |The window of values to find the sum of
  349. |===
  350. [source,js]
  351. --------------------------------------------------
  352. POST /_search
  353. {
  354. "size": 0,
  355. "aggs": {
  356. "my_date_histo":{
  357. "date_histogram":{
  358. "field":"date",
  359. "calendar_interval":"1M"
  360. },
  361. "aggs":{
  362. "the_sum":{
  363. "sum":{ "field": "price" }
  364. },
  365. "the_movavg": {
  366. "moving_fn": {
  367. "buckets_path": "the_sum",
  368. "window": 10,
  369. "script": "MovingFunctions.unweightedAvg(values)"
  370. }
  371. }
  372. }
  373. }
  374. }
  375. }
  376. --------------------------------------------------
  377. // CONSOLE
  378. // TEST[setup:sales]
  379. ==== linearWeightedAvg Function
  380. The `linearWeightedAvg` function assigns a linear weighting to points in the series, such that "older" datapoints (e.g. those at
  381. the beginning of the window) contribute a linearly less amount to the total average. The linear weighting helps reduce
  382. the "lag" behind the data's mean, since older points have less influence.
  383. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  384. [[linearweightedavg-params]]
  385. .`linearWeightedAvg(double[] values)` Parameters
  386. [options="header"]
  387. |===
  388. |Parameter Name |Description
  389. |`values` |The window of values to find the sum of
  390. |===
  391. [source,js]
  392. --------------------------------------------------
  393. POST /_search
  394. {
  395. "size": 0,
  396. "aggs": {
  397. "my_date_histo":{
  398. "date_histogram":{
  399. "field":"date",
  400. "calendar_interval":"1M"
  401. },
  402. "aggs":{
  403. "the_sum":{
  404. "sum":{ "field": "price" }
  405. },
  406. "the_movavg": {
  407. "moving_fn": {
  408. "buckets_path": "the_sum",
  409. "window": 10,
  410. "script": "MovingFunctions.linearWeightedAvg(values)"
  411. }
  412. }
  413. }
  414. }
  415. }
  416. }
  417. --------------------------------------------------
  418. // CONSOLE
  419. // TEST[setup:sales]
  420. ==== ewma Function
  421. The `ewma` function (aka "single-exponential") is similar to the `linearMovAvg` function,
  422. except older data-points become exponentially less important,
  423. rather than linearly less important. The speed at which the importance decays can be controlled with an `alpha`
  424. setting. Small values make the weight decay slowly, which provides greater smoothing and takes into account a larger
  425. portion of the window. Larger values make the weight decay quickly, which reduces the impact of older values on the
  426. moving average. This tends to make the moving average track the data more closely but with less smoothing.
  427. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  428. `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`
  429. values.
  430. [[ewma-params]]
  431. .`ewma(double[] values, double alpha)` Parameters
  432. [options="header"]
  433. |===
  434. |Parameter Name |Description
  435. |`values` |The window of values to find the sum of
  436. |`alpha` |Exponential decay
  437. |===
  438. [source,js]
  439. --------------------------------------------------
  440. POST /_search
  441. {
  442. "size": 0,
  443. "aggs": {
  444. "my_date_histo":{
  445. "date_histogram":{
  446. "field":"date",
  447. "calendar_interval":"1M"
  448. },
  449. "aggs":{
  450. "the_sum":{
  451. "sum":{ "field": "price" }
  452. },
  453. "the_movavg": {
  454. "moving_fn": {
  455. "buckets_path": "the_sum",
  456. "window": 10,
  457. "script": "MovingFunctions.ewma(values, 0.3)"
  458. }
  459. }
  460. }
  461. }
  462. }
  463. }
  464. --------------------------------------------------
  465. // CONSOLE
  466. // TEST[setup:sales]
  467. ==== holt Function
  468. The `holt` function (aka "double exponential") incorporates a second exponential term which
  469. tracks the data's trend. Single exponential does not perform well when the data has an underlying linear trend. The
  470. double exponential model calculates two values internally: a "level" and a "trend".
  471. The level calculation is similar to `ewma`, and is an exponentially weighted view of the data. The difference is
  472. that the previously smoothed value is used instead of the raw value, which allows it to stay close to the original series.
  473. The trend calculation looks at the difference between the current and last value (e.g. the slope, or trend, of the
  474. smoothed data). The trend value is also exponentially weighted.
  475. Values are produced by multiplying the level and trend components.
  476. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  477. `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`
  478. values.
  479. [[holt-params]]
  480. .`holt(double[] values, double alpha)` Parameters
  481. [options="header"]
  482. |===
  483. |Parameter Name |Description
  484. |`values` |The window of values to find the sum of
  485. |`alpha` |Level decay value
  486. |`beta` |Trend decay value
  487. |===
  488. [source,js]
  489. --------------------------------------------------
  490. POST /_search
  491. {
  492. "size": 0,
  493. "aggs": {
  494. "my_date_histo":{
  495. "date_histogram":{
  496. "field":"date",
  497. "calendar_interval":"1M"
  498. },
  499. "aggs":{
  500. "the_sum":{
  501. "sum":{ "field": "price" }
  502. },
  503. "the_movavg": {
  504. "moving_fn": {
  505. "buckets_path": "the_sum",
  506. "window": 10,
  507. "script": "MovingFunctions.holt(values, 0.3, 0.1)"
  508. }
  509. }
  510. }
  511. }
  512. }
  513. }
  514. --------------------------------------------------
  515. // CONSOLE
  516. // TEST[setup:sales]
  517. In practice, the `alpha` value behaves very similarly in `holtMovAvg` as `ewmaMovAvg`: small values produce more smoothing
  518. and more lag, while larger values produce closer tracking and less lag. The value of `beta` is often difficult
  519. to see. Small values emphasize long-term trends (such as a constant linear trend in the whole series), while larger
  520. values emphasize short-term trends.
  521. ==== holtWinters Function
  522. The `holtWinters` function (aka "triple exponential") incorporates a third exponential term which
  523. tracks the seasonal aspect of your data. This aggregation therefore smooths based on three components: "level", "trend"
  524. and "seasonality".
  525. The level and trend calculation is identical to `holt` The seasonal calculation looks at the difference between
  526. the current point, and the point one period earlier.
  527. Holt-Winters requires a little more handholding than the other moving averages. You need to specify the "periodicity"
  528. of your data: e.g. if your data has cyclic trends every 7 days, you would set `period = 7`. Similarly if there was
  529. a monthly trend, you would set it to `30`. There is currently no periodicity detection, although that is planned
  530. for future enhancements.
  531. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  532. `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`
  533. values.
  534. [[holtwinters-params]]
  535. .`holtWinters(double[] values, double alpha)` Parameters
  536. [options="header"]
  537. |===
  538. |Parameter Name |Description
  539. |`values` |The window of values to find the sum of
  540. |`alpha` |Level decay value
  541. |`beta` |Trend decay value
  542. |`gamma` |Seasonality decay value
  543. |`period` |The periodicity of the data
  544. |`multiplicative` |True if you wish to use multiplicative holt-winters, false to use additive
  545. |===
  546. [source,js]
  547. --------------------------------------------------
  548. POST /_search
  549. {
  550. "size": 0,
  551. "aggs": {
  552. "my_date_histo":{
  553. "date_histogram":{
  554. "field":"date",
  555. "calendar_interval":"1M"
  556. },
  557. "aggs":{
  558. "the_sum":{
  559. "sum":{ "field": "price" }
  560. },
  561. "the_movavg": {
  562. "moving_fn": {
  563. "buckets_path": "the_sum",
  564. "window": 10,
  565. "script": "if (values.length > 5*2) {MovingFunctions.holtWinters(values, 0.3, 0.1, 0.1, 5, false)}"
  566. }
  567. }
  568. }
  569. }
  570. }
  571. }
  572. --------------------------------------------------
  573. // CONSOLE
  574. // TEST[setup:sales]
  575. [WARNING]
  576. ======
  577. Multiplicative Holt-Winters works by dividing each data point by the seasonal value. This is problematic if any of
  578. your data is zero, or if there are gaps in the data (since this results in a divid-by-zero). To combat this, the
  579. `mult` Holt-Winters pads all values by a very small amount (1*10^-10^) so that all values are non-zero. This affects
  580. the result, but only minimally. If your data is non-zero, or you prefer to see `NaN` when zero's are encountered,
  581. you can disable this behavior with `pad: false`
  582. ======
  583. ===== "Cold Start"
  584. Unfortunately, due to the nature of Holt-Winters, it requires two periods of data to "bootstrap" the algorithm. This
  585. means that your `window` must always be *at least* twice the size of your period. An exception will be thrown if it
  586. isn't. It also means that Holt-Winters will not emit a value for the first `2 * period` buckets; the current algorithm
  587. does not backcast.
  588. You'll notice in the above example we have an `if ()` statement checking the size of values. This is checking to make sure
  589. we have two periods worth of data (`5 * 2`, where 5 is the period specified in the `holtWintersMovAvg` function) before calling
  590. the holt-winters function.