scripted-metric-aggregation.asciidoc 9.0 KB

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