using.asciidoc 15 KB

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