movfn-aggregation.asciidoc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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-avg-params]]
  22. .`moving_avg` 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. |===
  30. `moving_fn` aggregations must be embedded inside of a `histogram` or `date_histogram` aggregation. They can be
  31. embedded like any other metric aggregation:
  32. [source,js]
  33. --------------------------------------------------
  34. POST /_search
  35. {
  36. "size": 0,
  37. "aggs": {
  38. "my_date_histo":{ <1>
  39. "date_histogram":{
  40. "field":"date",
  41. "calendar_interval":"1M"
  42. },
  43. "aggs":{
  44. "the_sum":{
  45. "sum":{ "field": "price" } <2>
  46. },
  47. "the_movfn": {
  48. "moving_fn": {
  49. "buckets_path": "the_sum", <3>
  50. "window": 10,
  51. "script": "MovingFunctions.unweightedAvg(values)"
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }
  58. --------------------------------------------------
  59. // CONSOLE
  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,js]
  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. // CONSOLE
  153. // TEST[setup:sales]
  154. ==== Pre-built Functions
  155. For convenience, a number of functions have been prebuilt and are available inside the `moving_fn` script context:
  156. - `max()`
  157. - `min()`
  158. - `sum()`
  159. - `stdDev()`
  160. - `unweightedAvg()`
  161. - `linearWeightedAvg()`
  162. - `ewma()`
  163. - `holt()`
  164. - `holtWinters()`
  165. The functions are available from the `MovingFunctions` namespace. E.g. `MovingFunctions.max()`
  166. ===== max Function
  167. This function accepts a collection of doubles and returns the maximum value in that window. `null` and `NaN` values are ignored; the maximum
  168. is only calculated over the real values. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  169. [[max-params]]
  170. .`max(double[] values)` Parameters
  171. [options="header"]
  172. |===
  173. |Parameter Name |Description
  174. |`values` |The window of values to find the maximum
  175. |===
  176. [source,js]
  177. --------------------------------------------------
  178. POST /_search
  179. {
  180. "size": 0,
  181. "aggs": {
  182. "my_date_histo":{
  183. "date_histogram":{
  184. "field":"date",
  185. "calendar_interval":"1M"
  186. },
  187. "aggs":{
  188. "the_sum":{
  189. "sum":{ "field": "price" }
  190. },
  191. "the_moving_max": {
  192. "moving_fn": {
  193. "buckets_path": "the_sum",
  194. "window": 10,
  195. "script": "MovingFunctions.max(values)"
  196. }
  197. }
  198. }
  199. }
  200. }
  201. }
  202. --------------------------------------------------
  203. // CONSOLE
  204. // TEST[setup:sales]
  205. ===== min Function
  206. This function accepts a collection of doubles and returns the minimum value in that window. `null` and `NaN` values are ignored; the minimum
  207. is only calculated over the real values. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  208. [[min-params]]
  209. .`min(double[] values)` Parameters
  210. [options="header"]
  211. |===
  212. |Parameter Name |Description
  213. |`values` |The window of values to find the minimum
  214. |===
  215. [source,js]
  216. --------------------------------------------------
  217. POST /_search
  218. {
  219. "size": 0,
  220. "aggs": {
  221. "my_date_histo":{
  222. "date_histogram":{
  223. "field":"date",
  224. "calendar_interval":"1M"
  225. },
  226. "aggs":{
  227. "the_sum":{
  228. "sum":{ "field": "price" }
  229. },
  230. "the_moving_min": {
  231. "moving_fn": {
  232. "buckets_path": "the_sum",
  233. "window": 10,
  234. "script": "MovingFunctions.min(values)"
  235. }
  236. }
  237. }
  238. }
  239. }
  240. }
  241. --------------------------------------------------
  242. // CONSOLE
  243. // TEST[setup:sales]
  244. ===== sum Function
  245. This function accepts a collection of doubles and returns the sum of the values in that window. `null` and `NaN` values are ignored;
  246. 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.
  247. [[sum-params]]
  248. .`sum(double[] values)` Parameters
  249. [options="header"]
  250. |===
  251. |Parameter Name |Description
  252. |`values` |The window of values to find the sum of
  253. |===
  254. [source,js]
  255. --------------------------------------------------
  256. POST /_search
  257. {
  258. "size": 0,
  259. "aggs": {
  260. "my_date_histo":{
  261. "date_histogram":{
  262. "field":"date",
  263. "calendar_interval":"1M"
  264. },
  265. "aggs":{
  266. "the_sum":{
  267. "sum":{ "field": "price" }
  268. },
  269. "the_moving_sum": {
  270. "moving_fn": {
  271. "buckets_path": "the_sum",
  272. "window": 10,
  273. "script": "MovingFunctions.sum(values)"
  274. }
  275. }
  276. }
  277. }
  278. }
  279. }
  280. --------------------------------------------------
  281. // CONSOLE
  282. // TEST[setup:sales]
  283. ===== stdDev Function
  284. This function accepts a collection of doubles and average, then returns the standard deviation of the values in that window.
  285. `null` and `NaN` values are ignored; the sum is only calculated over the real values. If the window is empty, or all values are
  286. `null`/`NaN`, `0.0` is returned as the result.
  287. [[stddev-params]]
  288. .`stdDev(double[] values)` Parameters
  289. [options="header"]
  290. |===
  291. |Parameter Name |Description
  292. |`values` |The window of values to find the standard deviation of
  293. |`avg` |The average of the window
  294. |===
  295. [source,js]
  296. --------------------------------------------------
  297. POST /_search
  298. {
  299. "size": 0,
  300. "aggs": {
  301. "my_date_histo":{
  302. "date_histogram":{
  303. "field":"date",
  304. "calendar_interval":"1M"
  305. },
  306. "aggs":{
  307. "the_sum":{
  308. "sum":{ "field": "price" }
  309. },
  310. "the_moving_sum": {
  311. "moving_fn": {
  312. "buckets_path": "the_sum",
  313. "window": 10,
  314. "script": "MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))"
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. --------------------------------------------------
  322. // CONSOLE
  323. // TEST[setup:sales]
  324. The `avg` parameter must be provided to the standard deviation function because different styles of averages can be computed on the window
  325. (simple, linearly weighted, etc). The various moving averages that are detailed below can be used to calculate the average for the
  326. standard deviation function.
  327. ===== unweightedAvg Function
  328. The `unweightedAvg` function calculates the sum of all values in the window, then divides by the size of the window. It is effectively
  329. a simple arithmetic mean of the window. The simple moving average does not perform any time-dependent weighting, which means
  330. the values from a `simple` moving average tend to "lag" behind the real data.
  331. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  332. `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`
  333. values.
  334. [[unweightedavg-params]]
  335. .`unweightedAvg(double[] values)` Parameters
  336. [options="header"]
  337. |===
  338. |Parameter Name |Description
  339. |`values` |The window of values to find the sum of
  340. |===
  341. [source,js]
  342. --------------------------------------------------
  343. POST /_search
  344. {
  345. "size": 0,
  346. "aggs": {
  347. "my_date_histo":{
  348. "date_histogram":{
  349. "field":"date",
  350. "calendar_interval":"1M"
  351. },
  352. "aggs":{
  353. "the_sum":{
  354. "sum":{ "field": "price" }
  355. },
  356. "the_movavg": {
  357. "moving_fn": {
  358. "buckets_path": "the_sum",
  359. "window": 10,
  360. "script": "MovingFunctions.unweightedAvg(values)"
  361. }
  362. }
  363. }
  364. }
  365. }
  366. }
  367. --------------------------------------------------
  368. // CONSOLE
  369. // TEST[setup:sales]
  370. ==== linearWeightedAvg Function
  371. The `linearWeightedAvg` function assigns a linear weighting to points in the series, such that "older" datapoints (e.g. those at
  372. the beginning of the window) contribute a linearly less amount to the total average. The linear weighting helps reduce
  373. the "lag" behind the data's mean, since older points have less influence.
  374. If the window is empty, or all values are `null`/`NaN`, `NaN` is returned as the result.
  375. [[linearweightedavg-params]]
  376. .`linearWeightedAvg(double[] values)` Parameters
  377. [options="header"]
  378. |===
  379. |Parameter Name |Description
  380. |`values` |The window of values to find the sum of
  381. |===
  382. [source,js]
  383. --------------------------------------------------
  384. POST /_search
  385. {
  386. "size": 0,
  387. "aggs": {
  388. "my_date_histo":{
  389. "date_histogram":{
  390. "field":"date",
  391. "calendar_interval":"1M"
  392. },
  393. "aggs":{
  394. "the_sum":{
  395. "sum":{ "field": "price" }
  396. },
  397. "the_movavg": {
  398. "moving_fn": {
  399. "buckets_path": "the_sum",
  400. "window": 10,
  401. "script": "MovingFunctions.linearWeightedAvg(values)"
  402. }
  403. }
  404. }
  405. }
  406. }
  407. }
  408. --------------------------------------------------
  409. // CONSOLE
  410. // TEST[setup:sales]
  411. ==== ewma Function
  412. The `ewma` function (aka "single-exponential") is similar to the `linearMovAvg` function,
  413. except older data-points become exponentially less important,
  414. rather than linearly less important. The speed at which the importance decays can be controlled with an `alpha`
  415. setting. Small values make the weight decay slowly, which provides greater smoothing and takes into account a larger
  416. portion of the window. Larger values make the weight decay quickly, which reduces the impact of older values on the
  417. moving average. This tends to make the moving average track the data more closely but with less smoothing.
  418. `null` and `NaN` values are ignored; the average is only calculated over the real values. If the window is empty, or all values are
  419. `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`
  420. values.
  421. [[ewma-params]]
  422. .`ewma(double[] values, double alpha)` Parameters
  423. [options="header"]
  424. |===
  425. |Parameter Name |Description
  426. |`values` |The window of values to find the sum of
  427. |`alpha` |Exponential decay
  428. |===
  429. [source,js]
  430. --------------------------------------------------
  431. POST /_search
  432. {
  433. "size": 0,
  434. "aggs": {
  435. "my_date_histo":{
  436. "date_histogram":{
  437. "field":"date",
  438. "calendar_interval":"1M"
  439. },
  440. "aggs":{
  441. "the_sum":{
  442. "sum":{ "field": "price" }
  443. },
  444. "the_movavg": {
  445. "moving_fn": {
  446. "buckets_path": "the_sum",
  447. "window": 10,
  448. "script": "MovingFunctions.ewma(values, 0.3)"
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. --------------------------------------------------
  456. // CONSOLE
  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,js]
  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. // CONSOLE
  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,js]
  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. // CONSOLE
  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.