using.asciidoc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. [[modules-scripting-using]]
  2. == How to use scripts
  3. Wherever scripting is supported in the Elasticsearch API, the syntax follows
  4. the same pattern:
  5. [source,js]
  6. -------------------------------------
  7. "script": {
  8. "lang": "...", <1>
  9. "source" | "id": "...", <2>
  10. "params": { ... } <3>
  11. }
  12. -------------------------------------
  13. // NOTCONSOLE
  14. <1> The language the script is written in, which defaults to `painless`.
  15. <2> The script itself which may be specified as `source` for an inline script or `id` for a stored script.
  16. <3> Any named parameters that should be passed into the script.
  17. For example, the following script is used in a search request to return a
  18. <<script-fields, scripted field>>:
  19. [source,console]
  20. -------------------------------------
  21. PUT my-index-000001/_doc/1
  22. {
  23. "my_field": 5
  24. }
  25. GET my-index-000001/_search
  26. {
  27. "script_fields": {
  28. "my_doubled_field": {
  29. "script": {
  30. "lang": "expression",
  31. "source": "doc['my_field'] * multiplier",
  32. "params": {
  33. "multiplier": 2
  34. }
  35. }
  36. }
  37. }
  38. }
  39. -------------------------------------
  40. [discrete]
  41. === Script parameters
  42. `lang`::
  43. Specifies the language the script is written in. Defaults to `painless`.
  44. `source`, `id`::
  45. Specifies the source of the script. An `inline` script is specified
  46. `source` as in the example above. A `stored` script is specified `id`
  47. and is retrieved from the cluster state (see <<modules-scripting-stored-scripts,Stored Scripts>>).
  48. `params`::
  49. Specifies any named parameters that are passed into the script as
  50. variables.
  51. [IMPORTANT]
  52. [[prefer-params]]
  53. .Prefer parameters
  54. ========================================
  55. The first time Elasticsearch sees a new script, it compiles it and stores the
  56. compiled version in a cache. Compilation can be a heavy process.
  57. If you need to pass variables into the script, you should pass them in as
  58. named `params` instead of hard-coding values into the script itself. For
  59. example, if you want to be able to multiply a field value by different
  60. multipliers, don't hard-code the multiplier into the script:
  61. [source,js]
  62. ----------------------
  63. "source": "doc['my_field'] * 2"
  64. ----------------------
  65. // NOTCONSOLE
  66. Instead, pass it in as a named parameter:
  67. [source,js]
  68. ----------------------
  69. "source": "doc['my_field'] * multiplier",
  70. "params": {
  71. "multiplier": 2
  72. }
  73. ----------------------
  74. // NOTCONSOLE
  75. The first version has to be recompiled every time the multiplier changes. The
  76. second version is only compiled once.
  77. If you compile too many unique scripts within a small amount of time,
  78. Elasticsearch will reject the new dynamic scripts with a
  79. `circuit_breaking_exception` error. For most contexts, you can compile up to 75
  80. scripts per 5 minutes by default. For ingest contexts, the default script
  81. compilation rate is unlimited. You can change these settings dynamically by
  82. setting `script.context.$CONTEXT.max_compilations_rate` eg.
  83. `script.context.field.max_compilations_rate=100/10m`.
  84. ========================================
  85. [discrete]
  86. [[modules-scripting-short-script-form]]
  87. === Short script form
  88. A short script form can be used for brevity. In the short form, `script` is represented
  89. by a string instead of an object. This string contains the source of the script.
  90. Short form:
  91. [source,js]
  92. ----------------------
  93. "script": "ctx._source.my-int++"
  94. ----------------------
  95. // NOTCONSOLE
  96. The same script in the normal form:
  97. [source,js]
  98. ----------------------
  99. "script": {
  100. "source": "ctx._source.my-int++"
  101. }
  102. ----------------------
  103. // NOTCONSOLE
  104. [discrete]
  105. [[modules-scripting-stored-scripts]]
  106. === Stored scripts
  107. Scripts may be stored in and retrieved from the cluster state using the
  108. `_scripts` end-point.
  109. If the {es} {security-features} are enabled, you must have the following
  110. privileges to create, retrieve, and delete stored scripts:
  111. * cluster: `all` or `manage`
  112. For more information, see <<security-privileges>>.
  113. [discrete]
  114. ==== Request examples
  115. The following are examples of using a stored script that lives at
  116. `/_scripts/{id}`.
  117. First, create the script called `calculate-score` in the cluster state:
  118. [source,console]
  119. -----------------------------------
  120. POST _scripts/calculate-score
  121. {
  122. "script": {
  123. "lang": "painless",
  124. "source": "Math.log(_score * 2) + params.my_modifier"
  125. }
  126. }
  127. -----------------------------------
  128. // TEST[setup:my_index]
  129. You may also specify a context as part of the url path to compile a
  130. stored script against that specific context in the form of
  131. `/_scripts/{id}/{context}`:
  132. [source,console]
  133. -----------------------------------
  134. POST _scripts/calculate-score/score
  135. {
  136. "script": {
  137. "lang": "painless",
  138. "source": "Math.log(_score * 2) + params.my_modifier"
  139. }
  140. }
  141. -----------------------------------
  142. // TEST[setup:my_index]
  143. This same script can be retrieved with:
  144. [source,console]
  145. -----------------------------------
  146. GET _scripts/calculate-score
  147. -----------------------------------
  148. // TEST[continued]
  149. Stored scripts can be used by specifying the `id` parameters as follows:
  150. [source,console]
  151. --------------------------------------------------
  152. GET my-index-000001/_search
  153. {
  154. "query": {
  155. "script_score": {
  156. "query": {
  157. "match": {
  158. "message": "some message"
  159. }
  160. },
  161. "script": {
  162. "id": "calculate-score",
  163. "params": {
  164. "my_modifier": 2
  165. }
  166. }
  167. }
  168. }
  169. }
  170. --------------------------------------------------
  171. // TEST[continued]
  172. And deleted with:
  173. [source,console]
  174. -----------------------------------
  175. DELETE _scripts/calculate-score
  176. -----------------------------------
  177. // TEST[continued]
  178. [discrete]
  179. [[modules-scripting-search-templates]]
  180. === Search templates
  181. You can also use the `_scripts` API to store **search templates**. Search
  182. templates save specific <<search-search,search requests>> with placeholder
  183. values, called template parameters.
  184. You can use stored search templates to run searches without writing out the
  185. entire query. Just provide the stored template's ID and the template parameters.
  186. This is useful when you want to run a commonly used query quickly and without
  187. mistakes.
  188. Search templates use the https://mustache.github.io/mustache.5.html[mustache
  189. templating language]. See <<search-template>> for more information and examples.
  190. [discrete]
  191. [[modules-scripting-using-caching]]
  192. === Script caching
  193. All scripts are cached by default so that they only need to be recompiled
  194. when updates occur. By default, scripts do not have a time-based expiration, but
  195. you can change this behavior by using the `script.cache.expire` setting.
  196. You can configure the size of this cache by using the `script.cache.max_size` setting.
  197. For most contexts, the default cache size is `100`. For ingest contexts, the
  198. default cache size is `200`.
  199. NOTE: The size of scripts is limited to 65,535 bytes. This can be
  200. changed by setting `script.max_size_in_bytes` setting to increase that soft
  201. limit, but if scripts are really large then a
  202. <<modules-scripting-engine,native script engine>> should be considered.
  203. [[scripts-and-search-speed]]
  204. === Scripts and search speed
  205. Scripts can't make use of {es}'s index structures or related optimizations. This
  206. can sometimes result in slower search speeds.
  207. If you often use scripts to transform indexed data, you can speed up search by
  208. making these changes during ingest instead. However, that often means slower
  209. index speeds.
  210. .*Example*
  211. [%collapsible]
  212. =====
  213. An index, `my_test_scores`, contains two `long` fields:
  214. * `math_score`
  215. * `verbal_score`
  216. When running searches, users often use a script to sort results by the sum of
  217. these two field's values.
  218. [source,console]
  219. ----
  220. GET /my_test_scores/_search
  221. {
  222. "query": {
  223. "term": {
  224. "grad_year": "2099"
  225. }
  226. },
  227. "sort": [
  228. {
  229. "_script": {
  230. "type": "number",
  231. "script": {
  232. "source": "doc['math_score'].value + doc['verbal_score'].value"
  233. },
  234. "order": "desc"
  235. }
  236. }
  237. ]
  238. }
  239. ----
  240. // TEST[s/^/PUT my_test_scores\n/]
  241. To speed up search, you can perform this calculation during ingest and index the
  242. sum to a field instead.
  243. First, <<indices-put-mapping,add a new field>>, `total_score`, to the index. The
  244. `total_score` field will contain sum of the `math_score` and `verbal_score`
  245. field values.
  246. [source,console]
  247. ----
  248. PUT /my_test_scores/_mapping
  249. {
  250. "properties": {
  251. "total_score": {
  252. "type": "long"
  253. }
  254. }
  255. }
  256. ----
  257. // TEST[continued]
  258. Next, use an <<ingest,ingest pipeline>> containing the
  259. <<script-processor,`script`>> processor to calculate the sum of `math_score` and
  260. `verbal_score` and index it in the `total_score` field.
  261. [source,console]
  262. ----
  263. PUT _ingest/pipeline/my_test_scores_pipeline
  264. {
  265. "description": "Calculates the total test score",
  266. "processors": [
  267. {
  268. "script": {
  269. "source": "ctx.total_score = (ctx.math_score + ctx.verbal_score)"
  270. }
  271. }
  272. ]
  273. }
  274. ----
  275. // TEST[continued]
  276. To update existing data, use this pipeline to <<docs-reindex,reindex>> any
  277. documents from `my_test_scores` to a new index, `my_test_scores_2`.
  278. [source,console]
  279. ----
  280. POST /_reindex
  281. {
  282. "source": {
  283. "index": "my_test_scores"
  284. },
  285. "dest": {
  286. "index": "my_test_scores_2",
  287. "pipeline": "my_test_scores_pipeline"
  288. }
  289. }
  290. ----
  291. // TEST[continued]
  292. Continue using the pipeline to index any new documents to `my_test_scores_2`.
  293. [source,console]
  294. ----
  295. POST /my_test_scores_2/_doc/?pipeline=my_test_scores_pipeline
  296. {
  297. "student": "kimchy",
  298. "grad_year": "2099",
  299. "math_score": 800,
  300. "verbal_score": 800
  301. }
  302. ----
  303. // TEST[continued]
  304. These changes may slow indexing but allow for faster searches. Users can now
  305. sort searches made on `my_test_scores_2` using the `total_score` field instead
  306. of using a script.
  307. [source,console]
  308. ----
  309. GET /my_test_scores_2/_search
  310. {
  311. "query": {
  312. "term": {
  313. "grad_year": "2099"
  314. }
  315. },
  316. "sort": [
  317. {
  318. "total_score": {
  319. "order": "desc"
  320. }
  321. }
  322. ]
  323. }
  324. ----
  325. // TEST[continued]
  326. ////
  327. [source,console]
  328. ----
  329. DELETE /_ingest/pipeline/my_test_scores_pipeline
  330. ----
  331. // TEST[continued]
  332. [source,console-result]
  333. ----
  334. {
  335. "acknowledged": true
  336. }
  337. ----
  338. ////
  339. =====
  340. We recommend testing and benchmarking any indexing changes before deploying them
  341. in production.
  342. [discrete]
  343. [[modules-scripting-errors]]
  344. === Script errors
  345. Elasticsearch returns error details when there is a compliation or runtime
  346. exception. The contents of this response are useful for tracking down the
  347. problem.
  348. experimental[]
  349. The contents of `position` are experimental and subject to change.