scripted-metric-aggregation.asciidoc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 file 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. "file": "my_init_script"
  54. },
  55. "map_script" : {
  56. "file": "my_map_script"
  57. },
  58. "combine_script" : {
  59. "file": "my_combine_script"
  60. },
  61. "params": {
  62. "field": "amount", <1>
  63. "_agg": {} <2>
  64. },
  65. "reduce_script" : {
  66. "file": "my_reduce_script"
  67. }
  68. }
  69. }
  70. }
  71. }
  72. --------------------------------------------------
  73. // CONSOLE
  74. // TEST[setup:ledger]
  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 and index with 2 shards:
  126. [source,js]
  127. --------------------------------------------------
  128. PUT /transactions/stock/_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. ===== After init_script
  150. This is run once on each shard before any document collection is performed, and so we will have a copy on each shard:
  151. Shard A::
  152. +
  153. [source,js]
  154. --------------------------------------------------
  155. "params" : {
  156. "_agg" : {
  157. "transactions" : []
  158. }
  159. }
  160. --------------------------------------------------
  161. Shard B::
  162. +
  163. [source,js]
  164. --------------------------------------------------
  165. "params" : {
  166. "_agg" : {
  167. "transactions" : []
  168. }
  169. }
  170. --------------------------------------------------
  171. ===== After map_script
  172. Each shard collects its documents and runs the map_script on each document that is collected:
  173. Shard A::
  174. +
  175. [source,js]
  176. --------------------------------------------------
  177. "params" : {
  178. "_agg" : {
  179. "transactions" : [ 80, -30 ]
  180. }
  181. }
  182. --------------------------------------------------
  183. Shard B::
  184. +
  185. [source,js]
  186. --------------------------------------------------
  187. "params" : {
  188. "_agg" : {
  189. "transactions" : [ -10, 130 ]
  190. }
  191. }
  192. --------------------------------------------------
  193. ===== After combine_script
  194. 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
  195. shard (by summing the values in the transactions array) which is passed back to the coordinating node:
  196. Shard A:: 50
  197. Shard B:: 120
  198. ===== After reduce_script
  199. The reduce_script receives an `_aggs` array containing the result of the combine script for each shard:
  200. [source,js]
  201. --------------------------------------------------
  202. "_aggs" : [
  203. 50,
  204. 120
  205. ]
  206. --------------------------------------------------
  207. 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
  208. produce the response:
  209. [source,js]
  210. --------------------------------------------------
  211. {
  212. ...
  213. "aggregations": {
  214. "profit": {
  215. "value": 170
  216. }
  217. }
  218. }
  219. --------------------------------------------------
  220. ==== Other Parameters
  221. [horizontal]
  222. params:: Optional. An object whose contents will be passed as variables to the `init_script`, `map_script` and `combine_script`. This can be
  223. useful to allow the user to control the behavior of the aggregation and for storing state between the scripts. If this is not specified,
  224. the default is the equivalent of providing:
  225. +
  226. [source,js]
  227. --------------------------------------------------
  228. "params" : {
  229. "_agg" : {}
  230. }
  231. --------------------------------------------------