scripted-metric-aggregation.asciidoc 8.7 KB

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