scripted-metric-aggregation.asciidoc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. [[search-aggregations-metrics-scripted-metric-aggregation]]
  2. === Scripted Metric Aggregation
  3. experimental[]
  4. A metric aggregation that executes using scripts to provide a metric output.
  5. Example:
  6. [source,js]
  7. --------------------------------------------------
  8. POST ledger/_search?size=0
  9. {
  10. "query" : {
  11. "match_all" : {}
  12. },
  13. "aggs": {
  14. "profit": {
  15. "scripted_metric": {
  16. "init_script" : "params._agg.transactions = []",
  17. "map_script" : "params._agg.transactions.add(doc.type.value == 'sale' ? doc.amount.value : -1 * doc.amount.value)", <1>
  18. "combine_script" : "double profit = 0; for (t in params._agg.transactions) { profit += t } return profit",
  19. "reduce_script" : "double profit = 0; for (a in params._aggs) { profit += a } return profit"
  20. }
  21. }
  22. }
  23. }
  24. --------------------------------------------------
  25. // CONSOLE
  26. // TEST[setup:ledger]
  27. <1> `map_script` is the only required parameter
  28. The above aggregation demonstrates how one would use the script aggregation compute the total profit from sale and cost transactions.
  29. The response for the above aggregation:
  30. [source,js]
  31. --------------------------------------------------
  32. {
  33. "took": 218,
  34. ...
  35. "aggregations": {
  36. "profit": {
  37. "value": 240.0
  38. }
  39. }
  40. }
  41. --------------------------------------------------
  42. // TESTRESPONSE[s/"took": 218/"took": $body.took/]
  43. // TESTRESPONSE[s/\.\.\./"_shards": $body._shards, "hits": $body.hits, "timed_out": false,/]
  44. The above example can also be specified using stored scripts as follows:
  45. [source,js]
  46. --------------------------------------------------
  47. POST ledger/_search?size=0
  48. {
  49. "aggs": {
  50. "profit": {
  51. "scripted_metric": {
  52. "init_script" : {
  53. "id": "my_init_script"
  54. },
  55. "map_script" : {
  56. "id": "my_map_script"
  57. },
  58. "combine_script" : {
  59. "id": "my_combine_script"
  60. },
  61. "params": {
  62. "field": "amount", <1>
  63. "_agg": {} <2>
  64. },
  65. "reduce_script" : {
  66. "id": "my_reduce_script"
  67. }
  68. }
  69. }
  70. }
  71. }
  72. --------------------------------------------------
  73. // CONSOLE
  74. // TEST[setup:ledger,stored_scripted_metric_script]
  75. <1> script parameters for `init`, `map` and `combine` scripts must be specified
  76. in a global `params` object so that it can be share between the scripts.
  77. <2> if you specify script parameters then you must specify `"_agg": {}`.
  78. ////
  79. Verify this response as well but in a hidden block.
  80. [source,js]
  81. --------------------------------------------------
  82. {
  83. "took": 218,
  84. ...
  85. "aggregations": {
  86. "profit": {
  87. "value": 240.0
  88. }
  89. }
  90. }
  91. --------------------------------------------------
  92. // TESTRESPONSE[s/"took": 218/"took": $body.took/]
  93. // TESTRESPONSE[s/\.\.\./"_shards": $body._shards, "hits": $body.hits, "timed_out": false,/]
  94. ////
  95. For more details on specifying scripts see <<modules-scripting, script documentation>>.
  96. ==== Allowed return types
  97. Whilst any valid script object can be used within a single script, the scripts must return or store in the `_agg` object only the following types:
  98. * primitive types
  99. * String
  100. * Map (containing only keys and values of the types listed here)
  101. * Array (containing elements of only the types listed here)
  102. ==== Scope of scripts
  103. The scripted metric aggregation uses scripts at 4 stages of its execution:
  104. init_script:: Executed prior to any collection of documents. Allows the aggregation to set up any initial state.
  105. +
  106. In the above example, the `init_script` creates an array `transactions` in the `_agg` object.
  107. map_script:: Executed once per document collected. This is the only required script. If no combine_script is specified, the resulting state
  108. needs to be stored in an object named `_agg`.
  109. +
  110. In the above example, the `map_script` checks the value of the type field. If the value is 'sale' the value of the amount field
  111. is added to the transactions array. If the value of the type field is not 'sale' the negated value of the amount field is added
  112. to transactions.
  113. combine_script:: Executed once on each shard after document collection is complete. Allows the aggregation to consolidate the state returned from
  114. each shard. If a combine_script is not provided the combine phase will return the aggregation variable.
  115. +
  116. In the above example, the `combine_script` iterates through all the stored transactions, summing the values in the `profit` variable
  117. and finally returns `profit`.
  118. reduce_script:: Executed once on the coordinating node after all shards have returned their results. The script is provided with access to a
  119. variable `_aggs` which is an array of the result of the combine_script on each shard. If a reduce_script is not provided
  120. the reduce phase will return the `_aggs` variable.
  121. +
  122. In the above example, the `reduce_script` iterates through the `profit` returned by each shard summing the values before returning the
  123. final combined profit which will be returned in the response of the aggregation.
  124. ==== Worked Example
  125. Imagine a situation where you index the following documents into an index with 2 shards:
  126. [source,js]
  127. --------------------------------------------------
  128. PUT /transactions/_doc/_bulk?refresh
  129. {"index":{"_id":1}}
  130. {"type": "sale","amount": 80}
  131. {"index":{"_id":2}}
  132. {"type": "cost","amount": 10}
  133. {"index":{"_id":3}}
  134. {"type": "cost","amount": 30}
  135. {"index":{"_id":4}}
  136. {"type": "sale","amount": 130}
  137. --------------------------------------------------
  138. // CONSOLE
  139. Lets say that documents 1 and 3 end up on shard A and documents 2 and 4 end up on shard B. The following is a breakdown of what the aggregation result is
  140. at each stage of the example above.
  141. ===== Before init_script
  142. No params object was specified so the default params object is used:
  143. [source,js]
  144. --------------------------------------------------
  145. "params" : {
  146. "_agg" : {}
  147. }
  148. --------------------------------------------------
  149. // NOTCONSOLE
  150. ===== After init_script
  151. This is run once on each shard before any document collection is performed, and so we will have a copy on each shard:
  152. Shard A::
  153. +
  154. [source,js]
  155. --------------------------------------------------
  156. "params" : {
  157. "_agg" : {
  158. "transactions" : []
  159. }
  160. }
  161. --------------------------------------------------
  162. // NOTCONSOLE
  163. Shard B::
  164. +
  165. [source,js]
  166. --------------------------------------------------
  167. "params" : {
  168. "_agg" : {
  169. "transactions" : []
  170. }
  171. }
  172. --------------------------------------------------
  173. // NOTCONSOLE
  174. ===== After map_script
  175. Each shard collects its documents and runs the map_script on each document that is collected:
  176. Shard A::
  177. +
  178. [source,js]
  179. --------------------------------------------------
  180. "params" : {
  181. "_agg" : {
  182. "transactions" : [ 80, -30 ]
  183. }
  184. }
  185. --------------------------------------------------
  186. // NOTCONSOLE
  187. Shard B::
  188. +
  189. [source,js]
  190. --------------------------------------------------
  191. "params" : {
  192. "_agg" : {
  193. "transactions" : [ -10, 130 ]
  194. }
  195. }
  196. --------------------------------------------------
  197. // NOTCONSOLE
  198. ===== After combine_script
  199. The combine_script is executed on each shard after document collection is complete and reduces all the transactions down to a single profit figure for each
  200. shard (by summing the values in the transactions array) which is passed back to the coordinating node:
  201. Shard A:: 50
  202. Shard B:: 120
  203. ===== After reduce_script
  204. The reduce_script receives an `_aggs` array containing the result of the combine script for each shard:
  205. [source,js]
  206. --------------------------------------------------
  207. "_aggs" : [
  208. 50,
  209. 120
  210. ]
  211. --------------------------------------------------
  212. // NOTCONSOLE
  213. It reduces the responses for the shards down to a final overall profit figure (by summing the values) and returns this as the result of the aggregation to
  214. produce the response:
  215. [source,js]
  216. --------------------------------------------------
  217. {
  218. ...
  219. "aggregations": {
  220. "profit": {
  221. "value": 170
  222. }
  223. }
  224. }
  225. --------------------------------------------------
  226. // NOTCONSOLE
  227. ==== Other Parameters
  228. [horizontal]
  229. params:: Optional. An object whose contents will be passed as variables to the `init_script`, `map_script` and `combine_script`. This can be
  230. useful to allow the user to control the behavior of the aggregation and for storing state between the scripts. If this is not specified,
  231. the default is the equivalent of providing:
  232. +
  233. [source,js]
  234. --------------------------------------------------
  235. "params" : {
  236. "_agg" : {}
  237. }
  238. --------------------------------------------------
  239. // NOTCONSOLE
  240. ==== Empty Buckets
  241. If a parent bucket of the scripted metric aggregation does not collect any documents an empty aggregation response will be returned from the
  242. shard with a `null` value. In this case the `reduce_script`'s `_aggs` variable will contain `null` as a response from that shard.
  243. `reduce_script`'s should therefore expect and deal with `null` responses from shards.