using.asciidoc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. <<request-body-search-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. By default, up to 75 scripts per
  80. 5 minutes will be compiled for most contexts and 375 scripts per 5 minutes
  81. for ingest contexts. You can change these settings dynamically by setting
  82. `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.likes++"
  94. ----------------------
  95. // NOTCONSOLE
  96. The same script in the normal form:
  97. [source,js]
  98. ----------------------
  99. "script": {
  100. "source": "ctx._source.likes++"
  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:twitter]
  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:twitter]
  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 twitter/_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. By default, the cache size is `100`.
  198. NOTE: The size of scripts is limited to 65,535 bytes. This can be
  199. changed by setting `script.max_size_in_bytes` setting to increase that soft
  200. limit, but if scripts are really large then a
  201. <<modules-scripting-engine,native script engine>> should be considered.
  202. [[scripts-and-search-speed]]
  203. === Scripts and search speed
  204. Scripts can't make use of {es}'s index structures or related optimizations. This
  205. can sometimes result in slower search speeds.
  206. If you often use scripts to transform indexed data, you can speed up search by
  207. making these changes during ingest instead. However, that often means slower
  208. index speeds.
  209. .*Example*
  210. [%collapsible]
  211. =====
  212. An index, `my_test_scores`, contains two `long` fields:
  213. * `math_score`
  214. * `verbal_score`
  215. When running searches, users often use a script to sort results by the sum of
  216. these two field's values.
  217. [source,console]
  218. ----
  219. GET /my_test_scores/_search
  220. {
  221. "query": {
  222. "term": {
  223. "grad_year": "2099"
  224. }
  225. },
  226. "sort": [
  227. {
  228. "_script": {
  229. "type": "number",
  230. "script": {
  231. "source": "doc['math_score'].value + doc['verbal_score'].value"
  232. },
  233. "order": "desc"
  234. }
  235. }
  236. ]
  237. }
  238. ----
  239. // TEST[s/^/PUT my_test_scores\n/]
  240. To speed up search, you can perform this calculation during ingest and index the
  241. sum to a field instead.
  242. First, <<indices-put-mapping,add a new field>>, `total_score`, to the index. The
  243. `total_score` field will contain sum of the `math_score` and `verbal_score`
  244. field values.
  245. [source,console]
  246. ----
  247. PUT /my_test_scores/_mapping
  248. {
  249. "properties": {
  250. "total_score": {
  251. "type": "long"
  252. }
  253. }
  254. }
  255. ----
  256. // TEST[continued]
  257. Next, use an <<ingest,ingest pipeline>> containing the
  258. <<script-processor,`script`>> processor to calculate the sum of `math_score` and
  259. `verbal_score` and index it in the `total_score` field.
  260. [source,console]
  261. ----
  262. PUT _ingest/pipeline/my_test_scores_pipeline
  263. {
  264. "description": "Calculates the total test score",
  265. "processors": [
  266. {
  267. "script": {
  268. "source": "ctx.total_score = (ctx.math_score + ctx.verbal_score)"
  269. }
  270. }
  271. ]
  272. }
  273. ----
  274. // TEST[continued]
  275. To update existing data, use this pipeline to <<docs-reindex,reindex>> any
  276. documents from `my_test_scores` to a new index, `my_test_scores_2`.
  277. [source,console]
  278. ----
  279. POST /_reindex
  280. {
  281. "source": {
  282. "index": "my_test_scores"
  283. },
  284. "dest": {
  285. "index": "my_test_scores_2",
  286. "pipeline": "my_test_scores_pipeline"
  287. }
  288. }
  289. ----
  290. // TEST[continued]
  291. Continue using the pipeline to index any new documents to `my_test_scores_2`.
  292. [source,console]
  293. ----
  294. POST /my_test_scores_2/_doc/?pipeline=my_test_scores_pipeline
  295. {
  296. "student": "kimchy",
  297. "grad_year": "2099",
  298. "math_score": 800,
  299. "verbal_score": 800
  300. }
  301. ----
  302. // TEST[continued]
  303. These changes may slow indexing but allow for faster searches. Users can now
  304. sort searches made on `my_test_scores_2` using the `total_score` field instead
  305. of using a script.
  306. [source,console]
  307. ----
  308. GET /my_test_scores_2/_search
  309. {
  310. "query": {
  311. "term": {
  312. "grad_year": "2099"
  313. }
  314. },
  315. "sort": [
  316. {
  317. "total_score": {
  318. "order": "desc"
  319. }
  320. }
  321. ]
  322. }
  323. ----
  324. // TEST[continued]
  325. ////
  326. [source,console]
  327. ----
  328. DELETE /_ingest/pipeline/my_test_scores_pipeline
  329. ----
  330. // TEST[continued]
  331. [source,console-result]
  332. ----
  333. {
  334. "acknowledged": true
  335. }
  336. ----
  337. ////
  338. =====
  339. We recommend testing and benchmarking any indexing changes before deploying them
  340. in production.
  341. [discrete]
  342. [[modules-scripting-errors]]
  343. === Script errors
  344. Elasticsearch returns error details when there is a compliation or runtime
  345. exception. The contents of this response are useful for tracking down the
  346. problem.
  347. experimental[]
  348. The contents of `position` are experimental and subject to change.