painless.asciidoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. [[modules-scripting-painless]]
  2. === Painless Scripting Language
  3. experimental[The Painless scripting language is new and is still marked as experimental. The syntax or API may be changed in the future in non-backwards compatible ways if required.]
  4. _Painless_ is a simple, secure scripting language available in Elasticsearch
  5. by default. It is designed specifically for use with Elasticsearch and can
  6. safely be used with `inline` and `stored` scripting, which is enabled by
  7. default.
  8. The Painless syntax is similar to http://groovy-lang.org/index.html[Groovy].
  9. You can use Painless anywhere a script can be used in Elasticsearch. It is the
  10. default if you don't set the `lang` parameter but if you want to be explicit you
  11. can set the `lang` parameter to `painless`.
  12. [[painless-features]]
  13. [float]
  14. == Painless Features
  15. * Fast performance: https://benchmarks.elastic.co/index.html#search_qps_scripts[several times faster] than the alternatives.
  16. * Safety: Fine-grained whitelist with method call/field granularity. See
  17. <<painless-api-reference>> for a complete list of available classes and methods.
  18. * Optional typing: Variables and parameters can use explicit types or the dynamic `def` type.
  19. * Syntax: Extends Java's syntax with a subset of Groovy for ease of use. See the <<modules-scripting-painless-syntax, Syntax Overview>>.
  20. * Optimizations: Designed specifically for Elasticsearch scripting.
  21. [[painless-examples]]
  22. [float]
  23. == Painless Examples
  24. To illustrate how Painless works, let's load some hockey stats into an Elasticsearch index:
  25. [source,js]
  26. ----------------------------------------------------------------
  27. PUT hockey/player/_bulk?refresh
  28. {"index":{"_id":1}}
  29. {"first":"johnny","last":"gaudreau","goals":[9,27,1],"assists":[17,46,0],"gp":[26,82,1],"born":"1993/08/13"}
  30. {"index":{"_id":2}}
  31. {"first":"sean","last":"monohan","goals":[7,54,26],"assists":[11,26,13],"gp":[26,82,82],"born":"1994/10/12"}
  32. {"index":{"_id":3}}
  33. {"first":"jiri","last":"hudler","goals":[5,34,36],"assists":[11,62,42],"gp":[24,80,79],"born":"1984/01/04"}
  34. {"index":{"_id":4}}
  35. {"first":"micheal","last":"frolik","goals":[4,6,15],"assists":[8,23,15],"gp":[26,82,82],"born":"1988/02/17"}
  36. {"index":{"_id":5}}
  37. {"first":"sam","last":"bennett","goals":[5,0,0],"assists":[8,1,0],"gp":[26,1,0],"born":"1996/06/20"}
  38. {"index":{"_id":6}}
  39. {"first":"dennis","last":"wideman","goals":[0,26,15],"assists":[11,30,24],"gp":[26,81,82],"born":"1983/03/20"}
  40. {"index":{"_id":7}}
  41. {"first":"david","last":"jones","goals":[7,19,5],"assists":[3,17,4],"gp":[26,45,34],"born":"1984/08/10"}
  42. {"index":{"_id":8}}
  43. {"first":"tj","last":"brodie","goals":[2,14,7],"assists":[8,42,30],"gp":[26,82,82],"born":"1990/06/07"}
  44. {"index":{"_id":39}}
  45. {"first":"mark","last":"giordano","goals":[6,30,15],"assists":[3,30,24],"gp":[26,60,63],"born":"1983/10/03"}
  46. {"index":{"_id":10}}
  47. {"first":"mikael","last":"backlund","goals":[3,15,13],"assists":[6,24,18],"gp":[26,82,82],"born":"1989/03/17"}
  48. {"index":{"_id":11}}
  49. {"first":"joe","last":"colborne","goals":[3,18,13],"assists":[6,20,24],"gp":[26,67,82],"born":"1990/01/30"}
  50. ----------------------------------------------------------------
  51. // CONSOLE
  52. // TESTSETUP
  53. [float]
  54. === Accessing Doc Values from Painless
  55. Document values can be accessed from a `Map` named `doc`.
  56. For example, the following script calculates a player's total goals. This example uses a strongly typed `int` and a `for` loop.
  57. [source,js]
  58. ----------------------------------------------------------------
  59. GET hockey/_search
  60. {
  61. "query": {
  62. "function_score": {
  63. "script_score": {
  64. "script": {
  65. "lang": "painless",
  66. "inline": "int total = 0; for (int i = 0; i < doc['goals'].length; ++i) { total += doc['goals'][i]; } return total;"
  67. }
  68. }
  69. }
  70. }
  71. }
  72. ----------------------------------------------------------------
  73. // CONSOLE
  74. Alternatively, you could do the same thing using a script field instead of a function score:
  75. [source,js]
  76. ----------------------------------------------------------------
  77. GET hockey/_search
  78. {
  79. "query": {
  80. "match_all": {}
  81. },
  82. "script_fields": {
  83. "total_goals": {
  84. "script": {
  85. "lang": "painless",
  86. "inline": "int total = 0; for (int i = 0; i < doc['goals'].length; ++i) { total += doc['goals'][i]; } return total;"
  87. }
  88. }
  89. }
  90. }
  91. ----------------------------------------------------------------
  92. // CONSOLE
  93. The following example uses a Painless script to sort the players by their combined first and last names. The names are accessed using
  94. `doc['first'].value` and `doc['last'].value`.
  95. [source,js]
  96. ----------------------------------------------------------------
  97. GET hockey/_search
  98. {
  99. "query": {
  100. "match_all": {}
  101. },
  102. "sort": {
  103. "_script": {
  104. "type": "string",
  105. "order": "asc",
  106. "script": {
  107. "lang": "painless",
  108. "inline": "doc['first.keyword'].value + ' ' + doc['last.keyword'].value"
  109. }
  110. }
  111. }
  112. }
  113. ----------------------------------------------------------------
  114. // CONSOLE
  115. [float]
  116. === Updating Fields with Painless
  117. You can also easily update fields. You access the original source for a field as `ctx._source.<field-name>`.
  118. First, let's look at the source data for a player by submitting the following request:
  119. [source,js]
  120. ----------------------------------------------------------------
  121. GET hockey/_search
  122. {
  123. "stored_fields": [
  124. "_id",
  125. "_source"
  126. ],
  127. "query": {
  128. "term": {
  129. "_id": 1
  130. }
  131. }
  132. }
  133. ----------------------------------------------------------------
  134. // CONSOLE
  135. To change player 1's last name to `hockey`, simply set `ctx._source.last` to the new value:
  136. [source,js]
  137. ----------------------------------------------------------------
  138. POST hockey/player/1/_update
  139. {
  140. "script": {
  141. "lang": "painless",
  142. "inline": "ctx._source.last = params.last",
  143. "params": {
  144. "last": "hockey"
  145. }
  146. }
  147. }
  148. ----------------------------------------------------------------
  149. // CONSOLE
  150. You can also add fields to a document. For example, this script adds a new field that contains
  151. the player's nickname, _hockey_.
  152. [source,js]
  153. ----------------------------------------------------------------
  154. POST hockey/player/1/_update
  155. {
  156. "script": {
  157. "lang": "painless",
  158. "inline": "ctx._source.last = params.last; ctx._source.nick = params.nick",
  159. "params": {
  160. "last": "gaudreau",
  161. "nick": "hockey"
  162. }
  163. }
  164. }
  165. ----------------------------------------------------------------
  166. // CONSOLE
  167. [float]
  168. [[modules-scripting-painless-dates]]
  169. === Regular expressions
  170. Dates are a little different to work with than regular values. Here is an
  171. example returning the year of every player's birth:
  172. [source,js]
  173. ----------------------------------------------------------------
  174. GET hockey/_search
  175. {
  176. "script_fields": {
  177. "birth_year": {
  178. "script": {
  179. "inline": "doc.born.date.year"
  180. }
  181. }
  182. }
  183. }
  184. ----------------------------------------------------------------
  185. // CONSOLE
  186. The key here is that instead of indexing directly into `doc.born` like you would
  187. a normal field you have to call `doc.born.date` to get a
  188. <<painless-api-reference-org-joda-time-ReadableDateTime, `ReadableDateTime`>>.
  189. From there you can call methods like
  190. <<painless-api-reference-org-joda-time-ReadableDateTime-getYear-0, `getYear`>>,
  191. and <<painless-api-reference-org-joda-time-ReadableDateTime-getDayOfWeek-0, `getDayOfWeek`>>.
  192. In the example above `year` is a shortcut to `getYear()`.
  193. If the date field is a list then `date` will always return the first date. To
  194. access all the dates use `dates` instead of `date`.
  195. [float]
  196. [[modules-scripting-painless-regex]]
  197. === Regular expressions
  198. NOTE: Regexes are disabled by default because they circumvent Painless's
  199. protection against long running and memory hungry scripts. To make matters
  200. worse even innocuous looking regexes can have staggering performance and stack
  201. depth behavior. They remain an amazing powerful tool but are too scary to enable
  202. by default. To enable them yourself set `script.painless.regex.enabled: true` in
  203. `elasticsearch.yml`. We'd like very much to have a safe alternative
  204. implementation that can be enabled by default so check this space for later
  205. developments!
  206. Painless's native support for regular expressions has syntax constructs:
  207. * `/pattern/`: Pattern literals create patterns. This is the only way to create
  208. a pattern in painless. The pattern inside the ++/++'s are just
  209. http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html[Java regular expressions].
  210. See <<modules-scripting-painless-regex-flags>> for more.
  211. * `=~`: The find operator return a `boolean`, `true` if a subsequence of the
  212. text matches, `false` otherwise.
  213. * `==~`: The match operator returns a `boolean`, `true` if the text matches,
  214. `false` if it doesn't.
  215. Using the find operator (`=~`) you can update all hockey players with "b" in
  216. their last name:
  217. [source,js]
  218. ----------------------------------------------------------------
  219. POST hockey/player/_update_by_query
  220. {
  221. "script": {
  222. "lang": "painless",
  223. "inline": "if (ctx._source.last =~ /b/) {ctx._source.last += \"matched\"} else {ctx.op = 'noop'}"
  224. }
  225. }
  226. ----------------------------------------------------------------
  227. // CONSOLE
  228. Using the match operator (`==~`) you can update all the hockey players who's
  229. names start with a consonant and end with a vowel:
  230. [source,js]
  231. ----------------------------------------------------------------
  232. POST hockey/player/_update_by_query
  233. {
  234. "script": {
  235. "lang": "painless",
  236. "inline": "if (ctx._source.last ==~ /[^aeiou].*[aeiou]/) {ctx._source.last += \"matched\"} else {ctx.op = 'noop'}"
  237. }
  238. }
  239. ----------------------------------------------------------------
  240. // CONSOLE
  241. You can use the `Pattern.matcher` directly to get a `Matcher` instance and
  242. remove all of the vowels in all of their last names:
  243. [source,js]
  244. ----------------------------------------------------------------
  245. POST hockey/player/_update_by_query
  246. {
  247. "script": {
  248. "lang": "painless",
  249. "inline": "ctx._source.last = /[aeiou]/.matcher(ctx._source.last).replaceAll('')"
  250. }
  251. }
  252. ----------------------------------------------------------------
  253. // CONSOLE
  254. `Matcher.replaceAll` is just a call to Java's `Matcher`'s
  255. http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#replaceAll-java.lang.String-[replaceAll]
  256. method so it supports `$1` and `\1` for replacements:
  257. [source,js]
  258. ----------------------------------------------------------------
  259. POST hockey/player/_update_by_query
  260. {
  261. "script": {
  262. "lang": "painless",
  263. "inline": "ctx._source.last = /n([aeiou])/.matcher(ctx._source.last).replaceAll('$1')"
  264. }
  265. }
  266. ----------------------------------------------------------------
  267. // CONSOLE
  268. If you need more control over replacements you can call `replaceAll` on a
  269. `CharSequence` with a `Function<Matcher, String>` that builds the replacement.
  270. This does not support `$1` or `\1` to access replacements because you already
  271. have a reference to the matcher and can get them with `m.group(1)`.
  272. IMPORTANT: Calling `Matcher.find` inside of the function that builds the
  273. replacement is rude and will likely break the replacement process.
  274. This will make all of the vowels in the hockey player's last names upper case:
  275. [source,js]
  276. ----------------------------------------------------------------
  277. POST hockey/player/_update_by_query
  278. {
  279. "script": {
  280. "lang": "painless",
  281. "inline": "ctx._source.last = ctx._source.last.replaceAll(/[aeiou]/, m -> m.group().toUpperCase(Locale.ROOT))"
  282. }
  283. }
  284. ----------------------------------------------------------------
  285. // CONSOLE
  286. Or you can use the `CharSequence.replaceFirst` to make the first vowel in their
  287. last names upper case:
  288. [source,js]
  289. ----------------------------------------------------------------
  290. POST hockey/player/_update_by_query
  291. {
  292. "script": {
  293. "lang": "painless",
  294. "inline": "ctx._source.last = ctx._source.last.replaceFirst(/[aeiou]/, m -> m.group().toUpperCase(Locale.ROOT))"
  295. }
  296. }
  297. ----------------------------------------------------------------
  298. // CONSOLE
  299. Note: all of the `_update_by_query` examples above could really do with a
  300. `query` to limit the data that they pull back. While you *could* use a
  301. <<query-dsl-script-query>> it wouldn't be as efficient as using any other query
  302. because script queries aren't able to use the inverted index to limit the
  303. documents that they have to check.