painless-getting-started.asciidoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. [[painless-getting-started]]
  2. == Getting Started with Painless
  3. include::painless-description.asciidoc[]
  4. [[painless-examples]]
  5. === Painless Examples
  6. To illustrate how Painless works, let's load some hockey stats into an Elasticsearch index:
  7. [source,js]
  8. ----------------------------------------------------------------
  9. PUT hockey/player/_bulk?refresh
  10. {"index":{"_id":1}}
  11. {"first":"johnny","last":"gaudreau","goals":[9,27,1],"assists":[17,46,0],"gp":[26,82,1],"born":"1993/08/13"}
  12. {"index":{"_id":2}}
  13. {"first":"sean","last":"monohan","goals":[7,54,26],"assists":[11,26,13],"gp":[26,82,82],"born":"1994/10/12"}
  14. {"index":{"_id":3}}
  15. {"first":"jiri","last":"hudler","goals":[5,34,36],"assists":[11,62,42],"gp":[24,80,79],"born":"1984/01/04"}
  16. {"index":{"_id":4}}
  17. {"first":"micheal","last":"frolik","goals":[4,6,15],"assists":[8,23,15],"gp":[26,82,82],"born":"1988/02/17"}
  18. {"index":{"_id":5}}
  19. {"first":"sam","last":"bennett","goals":[5,0,0],"assists":[8,1,0],"gp":[26,1,0],"born":"1996/06/20"}
  20. {"index":{"_id":6}}
  21. {"first":"dennis","last":"wideman","goals":[0,26,15],"assists":[11,30,24],"gp":[26,81,82],"born":"1983/03/20"}
  22. {"index":{"_id":7}}
  23. {"first":"david","last":"jones","goals":[7,19,5],"assists":[3,17,4],"gp":[26,45,34],"born":"1984/08/10"}
  24. {"index":{"_id":8}}
  25. {"first":"tj","last":"brodie","goals":[2,14,7],"assists":[8,42,30],"gp":[26,82,82],"born":"1990/06/07"}
  26. {"index":{"_id":39}}
  27. {"first":"mark","last":"giordano","goals":[6,30,15],"assists":[3,30,24],"gp":[26,60,63],"born":"1983/10/03"}
  28. {"index":{"_id":10}}
  29. {"first":"mikael","last":"backlund","goals":[3,15,13],"assists":[6,24,18],"gp":[26,82,82],"born":"1989/03/17"}
  30. {"index":{"_id":11}}
  31. {"first":"joe","last":"colborne","goals":[3,18,13],"assists":[6,20,24],"gp":[26,67,82],"born":"1990/01/30"}
  32. ----------------------------------------------------------------
  33. // CONSOLE
  34. // TESTSETUP
  35. [float]
  36. ==== Accessing Doc Values from Painless
  37. Document values can be accessed from a `Map` named `doc`.
  38. For example, the following script calculates a player's total goals. This example uses a strongly typed `int` and a `for` loop.
  39. [source,js]
  40. ----------------------------------------------------------------
  41. GET hockey/_search
  42. {
  43. "query": {
  44. "function_score": {
  45. "script_score": {
  46. "script": {
  47. "lang": "painless",
  48. "source": """
  49. int total = 0;
  50. for (int i = 0; i < doc['goals'].length; ++i) {
  51. total += doc['goals'][i];
  52. }
  53. return total;
  54. """
  55. }
  56. }
  57. }
  58. }
  59. }
  60. ----------------------------------------------------------------
  61. // CONSOLE
  62. Alternatively, you could do the same thing using a script field instead of a function score:
  63. [source,js]
  64. ----------------------------------------------------------------
  65. GET hockey/_search
  66. {
  67. "query": {
  68. "match_all": {}
  69. },
  70. "script_fields": {
  71. "total_goals": {
  72. "script": {
  73. "lang": "painless",
  74. "source": """
  75. int total = 0;
  76. for (int i = 0; i < doc['goals'].length; ++i) {
  77. total += doc['goals'][i];
  78. }
  79. return total;
  80. """
  81. }
  82. }
  83. }
  84. }
  85. ----------------------------------------------------------------
  86. // CONSOLE
  87. The following example uses a Painless script to sort the players by their combined first and last names. The names are accessed using
  88. `doc['first'].value` and `doc['last'].value`.
  89. [source,js]
  90. ----------------------------------------------------------------
  91. GET hockey/_search
  92. {
  93. "query": {
  94. "match_all": {}
  95. },
  96. "sort": {
  97. "_script": {
  98. "type": "string",
  99. "order": "asc",
  100. "script": {
  101. "lang": "painless",
  102. "source": "doc['first.keyword'].value + ' ' + doc['last.keyword'].value"
  103. }
  104. }
  105. }
  106. }
  107. ----------------------------------------------------------------
  108. // CONSOLE
  109. [float]
  110. ===== Missing values
  111. `doc['field'].value` throws an exception if
  112. the field is missing in a document.
  113. To check if a document is missing a value, you can call
  114. `doc['field'].size() == 0`.
  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. "source": "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. "source": """
  159. ctx._source.last = params.last;
  160. ctx._source.nick = params.nick
  161. """,
  162. "params": {
  163. "last": "gaudreau",
  164. "nick": "hockey"
  165. }
  166. }
  167. }
  168. ----------------------------------------------------------------
  169. // CONSOLE
  170. [float]
  171. [[modules-scripting-painless-dates]]
  172. ==== Dates
  173. Date fields are exposed as
  174. `ReadableDateTime`, so they support methods like `getYear`, `getDayOfWeek`
  175. or e.g. getting milliseconds since epoch with `getMillis`. To use these
  176. in a script, leave out the `get` prefix and continue with lowercasing the
  177. rest of the method name. For example, the following returns every hockey
  178. player's birth year:
  179. [source,js]
  180. ----------------------------------------------------------------
  181. GET hockey/_search
  182. {
  183. "script_fields": {
  184. "birth_year": {
  185. "script": {
  186. "source": "doc.born.value.year"
  187. }
  188. }
  189. }
  190. }
  191. ----------------------------------------------------------------
  192. // CONSOLE
  193. [float]
  194. [[modules-scripting-painless-regex]]
  195. ==== Regular expressions
  196. NOTE: Regexes are disabled by default because they circumvent Painless's
  197. protection against long running and memory hungry scripts. To make matters
  198. worse even innocuous looking regexes can have staggering performance and stack
  199. depth behavior. They remain an amazing powerful tool but are too scary to enable
  200. by default. To enable them yourself set `script.painless.regex.enabled: true` in
  201. `elasticsearch.yml`. We'd like very much to have a safe alternative
  202. implementation that can be enabled by default so check this space for later
  203. developments!
  204. Painless's native support for regular expressions has syntax constructs:
  205. * `/pattern/`: Pattern literals create patterns. This is the only way to create
  206. a pattern in painless. The pattern inside the ++/++'s are just
  207. http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html[Java regular expressions].
  208. See <<pattern-flags>> for more.
  209. * `=~`: The find operator return a `boolean`, `true` if a subsequence of the
  210. text matches, `false` otherwise.
  211. * `==~`: The match operator returns a `boolean`, `true` if the text matches,
  212. `false` if it doesn't.
  213. Using the find operator (`=~`) you can update all hockey players with "b" in
  214. their last name:
  215. [source,js]
  216. ----------------------------------------------------------------
  217. POST hockey/_update_by_query
  218. {
  219. "script": {
  220. "lang": "painless",
  221. "source": """
  222. if (ctx._source.last =~ /b/) {
  223. ctx._source.last += "matched";
  224. } else {
  225. ctx.op = "noop";
  226. }
  227. """
  228. }
  229. }
  230. ----------------------------------------------------------------
  231. // CONSOLE
  232. Using the match operator (`==~`) you can update all the hockey players whose
  233. names start with a consonant and end with a vowel:
  234. [source,js]
  235. ----------------------------------------------------------------
  236. POST hockey/_update_by_query
  237. {
  238. "script": {
  239. "lang": "painless",
  240. "source": """
  241. if (ctx._source.last ==~ /[^aeiou].*[aeiou]/) {
  242. ctx._source.last += "matched";
  243. } else {
  244. ctx.op = "noop";
  245. }
  246. """
  247. }
  248. }
  249. ----------------------------------------------------------------
  250. // CONSOLE
  251. You can use the `Pattern.matcher` directly to get a `Matcher` instance and
  252. remove all of the vowels in all of their last names:
  253. [source,js]
  254. ----------------------------------------------------------------
  255. POST hockey/_update_by_query
  256. {
  257. "script": {
  258. "lang": "painless",
  259. "source": "ctx._source.last = /[aeiou]/.matcher(ctx._source.last).replaceAll('')"
  260. }
  261. }
  262. ----------------------------------------------------------------
  263. // CONSOLE
  264. `Matcher.replaceAll` is just a call to Java's `Matcher`'s
  265. http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#replaceAll-java.lang.String-[replaceAll]
  266. method so it supports `$1` and `\1` for replacements:
  267. [source,js]
  268. ----------------------------------------------------------------
  269. POST hockey/_update_by_query
  270. {
  271. "script": {
  272. "lang": "painless",
  273. "source": "ctx._source.last = /n([aeiou])/.matcher(ctx._source.last).replaceAll('$1')"
  274. }
  275. }
  276. ----------------------------------------------------------------
  277. // CONSOLE
  278. If you need more control over replacements you can call `replaceAll` on a
  279. `CharSequence` with a `Function<Matcher, String>` that builds the replacement.
  280. This does not support `$1` or `\1` to access replacements because you already
  281. have a reference to the matcher and can get them with `m.group(1)`.
  282. IMPORTANT: Calling `Matcher.find` inside of the function that builds the
  283. replacement is rude and will likely break the replacement process.
  284. This will make all of the vowels in the hockey player's last names upper case:
  285. [source,js]
  286. ----------------------------------------------------------------
  287. POST hockey/_update_by_query
  288. {
  289. "script": {
  290. "lang": "painless",
  291. "source": """
  292. ctx._source.last = ctx._source.last.replaceAll(/[aeiou]/, m ->
  293. m.group().toUpperCase(Locale.ROOT))
  294. """
  295. }
  296. }
  297. ----------------------------------------------------------------
  298. // CONSOLE
  299. Or you can use the `CharSequence.replaceFirst` to make the first vowel in their
  300. last names upper case:
  301. [source,js]
  302. ----------------------------------------------------------------
  303. POST hockey/_update_by_query
  304. {
  305. "script": {
  306. "lang": "painless",
  307. "source": """
  308. ctx._source.last = ctx._source.last.replaceFirst(/[aeiou]/, m ->
  309. m.group().toUpperCase(Locale.ROOT))
  310. """
  311. }
  312. }
  313. ----------------------------------------------------------------
  314. // CONSOLE
  315. Note: all of the `_update_by_query` examples above could really do with a
  316. `query` to limit the data that they pull back. While you *could* use a
  317. {ref}/query-dsl-script-query.html[script query] it wouldn't be as efficient
  318. as using any other query because script queries aren't able to use the inverted
  319. index to limit the documents that they have to check.
  320. [[modules-scripting-painless-dispatch]]
  321. === How painless dispatches functions
  322. Painless uses receiver, name, and https://en.wikipedia.org/wiki/Arity[arity]
  323. for method dispatch. For example, `s.foo(a, b)` is resolved by first getting
  324. the class of `s` and then looking up the method `foo` with two parameters. This
  325. is different from Groovy which uses the
  326. https://en.wikipedia.org/wiki/Multiple_dispatch[runtime types] of the
  327. parameters and Java which uses the compile time types of the parameters.
  328. The consequence of this that Painless doesn't support overloaded methods like
  329. Java, leading to some trouble when it whitelists classes from the Java
  330. standard library. For example, in Java and Groovy, `Matcher` has two methods:
  331. `group(int)` and `group(String)`. Painless can't whitelist both of these methods
  332. because they have the same name and the same number of parameters. So instead it
  333. has `group(int)` and `namedGroup(String)`.
  334. We have a few justifications for this different way of dispatching methods:
  335. 1. It makes operating on `def` types simpler and, presumably, faster. Using
  336. receiver, name, and arity means that when Painless sees a call on a `def` object it
  337. can dispatch the appropriate method without having to do expensive comparisons
  338. of the types of the parameters. The same is true for invocations with `def`
  339. typed parameters.
  340. 2. It keeps things consistent. It would be genuinely weird for Painless to
  341. behave like Groovy if any `def` typed parameters were involved and Java
  342. otherwise. It'd be slow for it to behave like Groovy all the time.
  343. 3. It keeps Painless maintainable. Adding the Java or Groovy like method
  344. dispatch *feels* like it'd add a ton of complexity which'd make maintenance and
  345. other improvements much more difficult.
  346. include::painless-debugging.asciidoc[]
  347. include::painless-execute-script.asciidoc[]