movfn-aggregation.asciidoc 22 KB

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