using.asciidoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. [[modules-scripting-using]]
  2. == How to write scripts
  3. Wherever scripting is supported in the {es} APIs, the syntax follows the same
  4. pattern; you specify the language of your script, provide the script logic (or
  5. source, and add parameters that are passed into the script:
  6. [source,js]
  7. -------------------------------------
  8. "script": {
  9. "lang": "...",
  10. "source" | "id": "...",
  11. "params": { ... }
  12. }
  13. -------------------------------------
  14. // NOTCONSOLE
  15. `lang`::
  16. Specifies the language the script is written in. Defaults to `painless`.
  17. `source`, `id`::
  18. The script itself, which you specify as `source` for an inline script or `id` for a stored script. Use the `_scripts` endpoint to retrieve a stored script. For example, you can create or delete a <<script-stored-scripts,stored script>> by calling `POST _scripts/{id}` and `DELETE _scripts/{id}`.
  19. `params`::
  20. Specifies any named parameters that are passed into the script as
  21. variables. <<prefer-params,Use parameters>> instead of hard-coded values to decrease compile time.
  22. [discrete]
  23. [[hello-world-script]]
  24. === Write your first script
  25. <<modules-scripting-painless,Painless>> is the default scripting language
  26. for {es}. It is secure, performant, and provides a natural syntax for anyone
  27. with a little coding experience.
  28. A Painless script is structured as one or more statements and optionally
  29. has one or more user-defined functions at the beginning. A script must always
  30. have at least one statement.
  31. The {painless}/painless-execute-api.html[Painless execute API] provides the ability to
  32. test a script with simple user-defined parameters and receive a result. Let's
  33. start with a complete script and review its constituent parts.
  34. First, index a document with a single field so that we have some data to work
  35. with:
  36. [source,console]
  37. ----
  38. PUT my-index-000001/_doc/1
  39. {
  40. "my_field": 5
  41. }
  42. ----
  43. We can then construct a script that operates on that field and run evaluate the
  44. script as part of a query. The following query uses the
  45. <<script-fields,`script_fields`>> parameter of the search API to retrieve a
  46. script valuation. There's a lot happening here, but we'll break it down the
  47. components to understand them individually. For now, you only need to
  48. understand that this script takes `my_field` and operates on it.
  49. [source,console]
  50. ----
  51. GET my-index-000001/_search
  52. {
  53. "script_fields": {
  54. "my_doubled_field": {
  55. "script": { <1>
  56. "source": "doc['my_field'].value * params['multiplier']", <2>
  57. "params": {
  58. "multiplier": 2
  59. }
  60. }
  61. }
  62. }
  63. }
  64. ----
  65. // TEST[continued]
  66. <1> `script` object
  67. <2> `script` source
  68. The `script` is a standard JSON object that defines scripts under most APIs
  69. in {es}. This object requires `source` to define the script itself. The
  70. script doesn't specify a language, so it defaults to Painless.
  71. [discrete]
  72. [[prefer-params]]
  73. === Use parameters in your script
  74. The first time {es} sees a new script, it compiles the script and stores the
  75. compiled version in a cache. Compilation can be a heavy process. Rather than
  76. hard-coding values in your script, pass them as named `params` instead.
  77. For example, in the previous script, we could have just hard coded values and
  78. written a script that is seemingly less complex. We could just retrieve the
  79. first value for `my_field` and then multiply it by `2`:
  80. [source,painless]
  81. ----
  82. "source": "return doc['my_field'].value * 2"
  83. ----
  84. Though it works, this solution is pretty inflexible. We have to modify the
  85. script source to change the multiplier, and {es} has to recompile the script
  86. every time that the multiplier changes.
  87. Instead of hard-coding values, use named `params` to make scripts flexible, and
  88. also reduce compilation time when the script runs. You can now make changes to
  89. the `multiplier` parameter without {es} recompiling the script.
  90. [source,painless]
  91. ----
  92. "source": "doc['my_field'].value * params['multiplier']",
  93. "params": {
  94. "multiplier": 2
  95. }
  96. ----
  97. For most contexts, you can compile up to 75 scripts per 5 minutes by default.
  98. For ingest contexts, the default script compilation rate is unlimited. You
  99. can change these settings dynamically by setting
  100. `script.context.$CONTEXT.max_compilations_rate`. For example, the following
  101. setting limits script compilation to 100 scripts every 10 minutes for the
  102. {painless}/painless-field-context.html[field context]:
  103. [source,js]
  104. ----
  105. script.context.field.max_compilations_rate=100/10m
  106. ----
  107. // NOTCONSOLE
  108. IMPORTANT: If you compile too many unique scripts within a short time, {es}
  109. rejects the new dynamic scripts with a `circuit_breaking_exception` error.
  110. [discrete]
  111. [[script-shorten-syntax]]
  112. === Shorten your script
  113. Using syntactic abilities that are native to Painless, you can reduce verbosity
  114. in your scripts and make them shorter. Here's a simple script that we can make
  115. shorter:
  116. [source,console]
  117. ----
  118. GET my-index-000001/_search
  119. {
  120. "script_fields": {
  121. "my_doubled_field": {
  122. "script": {
  123. "lang": "painless",
  124. "source": "return doc['my_field'].value * params.get('multiplier');",
  125. "params": {
  126. "multiplier": 2
  127. }
  128. }
  129. }
  130. }
  131. }
  132. ----
  133. // TEST[s/^/PUT my-index-000001\n/]
  134. Let's look at a shortened version of the script to see what improvements it
  135. includes over the previous iteration:
  136. [source,console]
  137. ----
  138. GET my-index-000001/_search
  139. {
  140. "script_fields": {
  141. "my_doubled_field": {
  142. "script": {
  143. "source": "doc['my_field'].value * params['multiplier']",
  144. "params": {
  145. "multiplier": 2
  146. }
  147. }
  148. }
  149. }
  150. }
  151. ----
  152. // TEST[s/^/PUT my-index-000001\n/]
  153. This version of the script removes several components and simplifies the syntax
  154. significantly:
  155. * The `lang` declaration. Because Painless is the default language, you don't
  156. need to specify the language if you're writing a Painless script.
  157. * The `return` keyword. Painless automatically uses the final statement in a
  158. script (when possible) to produce a return value in a script context that
  159. requires one.
  160. * The `get` method, which is replaced with brackets `[]`. Painless
  161. uses a shortcut specifically for the `Map` type that allows us to use brackets
  162. instead of the lengthier `get` method.
  163. * The semicolon at the end of the `source` statement. Painless does not
  164. require semicolons for the final statement of a block. However, it does require
  165. them in other cases to remove ambiguity.
  166. Use this abbreviated syntax anywhere that {es} supports scripts, such as
  167. when you're creating <<runtime-mapping-fields,runtime fields>>.
  168. [discrete]
  169. [[script-stored-scripts]]
  170. === Store and retrieve scripts
  171. You can store and retrieve scripts from the cluster state using the `_scripts`
  172. endpoint. Using stored scripts can help to reduce compilation time and make
  173. searches faster. Use the `{id}` path element in `_scripts/{id}` to refer to a
  174. stored script.
  175. NOTE: Unlike regular scripts, stored scripts require that you specify a script
  176. language using the `lang` parameter.
  177. For example, let's create a stored script in the cluster named
  178. `calculate-score`:
  179. [source,console]
  180. -----------------------------------
  181. POST _scripts/calculate-score
  182. {
  183. "script": {
  184. "lang": "painless",
  185. "source": "Math.log(_score * 2) + params['my_modifier']"
  186. }
  187. }
  188. -----------------------------------
  189. // TEST[setup:my_index]
  190. You can retrieve that script by using the `_scripts` endpoint:
  191. [source,console]
  192. -----------------------------------
  193. GET _scripts/calculate-score
  194. -----------------------------------
  195. // TEST[continued]
  196. To use the stored script in a query, include the script `id` in the `script`
  197. declaration:
  198. [source,console]
  199. ----
  200. GET my-index-000001/_search
  201. {
  202. "query": {
  203. "script_score": {
  204. "query": {
  205. "match": {
  206. "message": "some message"
  207. }
  208. },
  209. "script": {
  210. "id": "calculate-score", <1>
  211. "params": {
  212. "my_modifier": 2
  213. }
  214. }
  215. }
  216. }
  217. }
  218. ----
  219. // TEST[continued]
  220. <1> `id` of the stored script
  221. To delete a stored script, submit a delete request to the `_scripts` endpoint
  222. and specify the stored script `id`:
  223. [source,console]
  224. ----
  225. DELETE _scripts/calculate-score
  226. ----
  227. // TEST[continued]
  228. [discrete]
  229. [[scripts-update-scripts]]
  230. === Update documents with scripts
  231. You can use the <<docs-update,update API>> to update documents with a specified
  232. script. The script can update, delete, or skip modifying the document. The
  233. update API also supports passing a partial document, which is merged into the
  234. existing document.
  235. First, let's index a simple document:
  236. [source,console]
  237. ----
  238. PUT my-index-000001/_doc/1
  239. {
  240. "counter" : 1,
  241. "tags" : ["red"]
  242. }
  243. ----
  244. To increment the counter, you can submit an update request with the following
  245. script:
  246. [source,console]
  247. ----
  248. POST my-index-000001/_update/1
  249. {
  250. "script" : {
  251. "source": "ctx._source.counter += params.count",
  252. "lang": "painless",
  253. "params" : {
  254. "count" : 4
  255. }
  256. }
  257. }
  258. ----
  259. // TEST[continued]
  260. Similarly, you can use an update script to add a tag to the list of tags.
  261. Because this is just a list, the tag is added even it exists:
  262. [source,console]
  263. ----
  264. POST my-index-000001/_update/1
  265. {
  266. "script": {
  267. "source": "ctx._source.tags.add(params['tag'])",
  268. "lang": "painless",
  269. "params": {
  270. "tag": "blue"
  271. }
  272. }
  273. }
  274. ----
  275. // TEST[continued]
  276. You can also remove a tag from the list of tags. The `remove` method of a Java
  277. `List` is available in Painless. It takes the index of the element you
  278. want to remove. To avoid a possible runtime error, you first need to make sure
  279. the tag exists. If the list contains duplicates of the tag, this script just
  280. removes one occurrence.
  281. [source,console]
  282. ----
  283. POST my-index-000001/_update/1
  284. {
  285. "script": {
  286. "source": "if (ctx._source.tags.contains(params['tag'])) { ctx._source.tags.remove(ctx._source.tags.indexOf(params['tag'])) }",
  287. "lang": "painless",
  288. "params": {
  289. "tag": "blue"
  290. }
  291. }
  292. }
  293. ----
  294. // TEST[continued]
  295. You can also add and remove fields from a document. For example, this script
  296. adds the field `new_field`:
  297. [source,console]
  298. ----
  299. POST my-index-000001/_update/1
  300. {
  301. "script" : "ctx._source.new_field = 'value_of_new_field'"
  302. }
  303. ----
  304. // TEST[continued]
  305. Conversely, this script removes the field `new_field`:
  306. [source,console]
  307. ----
  308. POST my-index-000001/_update/1
  309. {
  310. "script" : "ctx._source.remove('new_field')"
  311. }
  312. ----
  313. // TEST[continued]
  314. Instead of updating the document, you can also change the operation that is
  315. executed from within the script. For example, this request deletes the document
  316. if the `tags` field contains `green`. Otherwise it does nothing (`noop`):
  317. [source,console]
  318. ----
  319. POST my-index-000001/_update/1
  320. {
  321. "script": {
  322. "source": "if (ctx._source.tags.contains(params['tag'])) { ctx.op = 'delete' } else { ctx.op = 'none' }",
  323. "lang": "painless",
  324. "params": {
  325. "tag": "green"
  326. }
  327. }
  328. }
  329. ----
  330. // TEST[continued]
  331. [[scripts-and-search-speed]]
  332. === Scripts, caching, and search speed
  333. {es} performs a number of optimizations to make using scripts as fast as
  334. possible. One important optimization is a script cache. The compiled script is
  335. placed in a cache so that requests that reference the script do not incur a
  336. compilation penalty.
  337. Cache sizing is important. Your script cache should be large enough to hold all
  338. of the scripts that users need to be accessed concurrently.
  339. If you see a large number of script cache evictions and a rising number of
  340. compilations in <<cluster-nodes-stats,node stats>>, your cache might be too
  341. small.
  342. All scripts are cached by default so that they only need to be recompiled
  343. when updates occur. By default, scripts do not have a time-based expiration.
  344. You can change this behavior by using the `script.cache.expire` setting.
  345. Use the `script.cache.max_size` setting to configure the size of the cache.
  346. NOTE: The size of scripts is limited to 65,535 bytes. Set the value of `script.max_size_in_bytes` to increase that soft limit. If your scripts are
  347. really large, then consider using a
  348. <<modules-scripting-engine,native script engine>>.
  349. [discrete]
  350. ==== Improving search speed
  351. Scripts are incredibly useful, but can't use {es}'s index structures or related
  352. optimizations. This relationship can sometimes result in slower search speeds.
  353. If you often use scripts to transform indexed data, you can make search faster
  354. by transforming data during ingest instead. However, that often means slower
  355. index speeds. Let's look at a practical example to illustrate how you can
  356. increase search speed.
  357. When running searches, it's common to sort results by the sum of two values.
  358. For example, consider an index named `my_test_scores` that contains test score
  359. data. This index includes two fields of type `long`:
  360. * `math_score`
  361. * `verbal_score`
  362. You can run a query with a script that adds these values together. There's
  363. nothing wrong with this approach, but the query will be slower because the
  364. script valuation occurs as part of the request. The following request returns
  365. documents where `grad_year` equals `2099`, and sorts by the results by the
  366. valuation of the script.
  367. [source,console]
  368. ----
  369. GET /my_test_scores/_search
  370. {
  371. "query": {
  372. "term": {
  373. "grad_year": "2099"
  374. }
  375. },
  376. "sort": [
  377. {
  378. "_script": {
  379. "type": "number",
  380. "script": {
  381. "source": "doc['math_score'].value + doc['verbal_score'].value"
  382. },
  383. "order": "desc"
  384. }
  385. }
  386. ]
  387. }
  388. ----
  389. // TEST[s/^/PUT my_test_scores\n/]
  390. If you're searching a small index, then including the script as part of your
  391. search query can be a good solution. If you want to make search faster, you can
  392. perform this calculation during ingest and index the sum to a field instead.
  393. First, we'll add a new field to the index named `total_score`, which will
  394. contain sum of the `math_score` and `verbal_score` field values.
  395. [source,console]
  396. ----
  397. PUT /my_test_scores/_mapping
  398. {
  399. "properties": {
  400. "total_score": {
  401. "type": "long"
  402. }
  403. }
  404. }
  405. ----
  406. // TEST[continued]
  407. Next, use an <<ingest,ingest pipeline>> containing the
  408. <<script-processor,script processor>> to calculate the sum of `math_score` and
  409. `verbal_score` and index it in the `total_score` field.
  410. [source,console]
  411. ----
  412. PUT _ingest/pipeline/my_test_scores_pipeline
  413. {
  414. "description": "Calculates the total test score",
  415. "processors": [
  416. {
  417. "script": {
  418. "source": "ctx.total_score = (ctx.math_score + ctx.verbal_score)"
  419. }
  420. }
  421. ]
  422. }
  423. ----
  424. // TEST[continued]
  425. To update existing data, use this pipeline to <<docs-reindex,reindex>> any
  426. documents from `my_test_scores` to a new index named `my_test_scores_2`.
  427. [source,console]
  428. ----
  429. POST /_reindex
  430. {
  431. "source": {
  432. "index": "my_test_scores"
  433. },
  434. "dest": {
  435. "index": "my_test_scores_2",
  436. "pipeline": "my_test_scores_pipeline"
  437. }
  438. }
  439. ----
  440. // TEST[continued]
  441. Continue using the pipeline to index any new documents to `my_test_scores_2`.
  442. [source,console]
  443. ----
  444. POST /my_test_scores_2/_doc/?pipeline=my_test_scores_pipeline
  445. {
  446. "student": "kimchy",
  447. "grad_year": "2099",
  448. "math_score": 1200,
  449. "verbal_score": 800
  450. }
  451. ----
  452. // TEST[continued]
  453. These changes slow the index process, but allow for faster searches. Instead of
  454. using a script, you can sort searches made on `my_test_scores_2` using the
  455. `total_score` field. The response is near real-time! Though this process slows
  456. ingest time, it greatly increases queries at search time.
  457. [source,console]
  458. ----
  459. GET /my_test_scores_2/_search
  460. {
  461. "query": {
  462. "term": {
  463. "grad_year": "2099"
  464. }
  465. },
  466. "sort": [
  467. {
  468. "total_score": {
  469. "order": "desc"
  470. }
  471. }
  472. ]
  473. }
  474. ----
  475. // TEST[continued]
  476. ////
  477. [source,console]
  478. ----
  479. DELETE /_ingest/pipeline/my_test_scores_pipeline
  480. ----
  481. // TEST[continued]
  482. ////