painless-getting-started.asciidoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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": "int total = 0; for (int i = 0; i < doc['goals'].length; ++i) { total += doc['goals'][i]; } return total;"
  49. }
  50. }
  51. }
  52. }
  53. }
  54. ----------------------------------------------------------------
  55. // CONSOLE
  56. Alternatively, you could do the same thing using a script field instead of a function score:
  57. [source,js]
  58. ----------------------------------------------------------------
  59. GET hockey/_search
  60. {
  61. "query": {
  62. "match_all": {}
  63. },
  64. "script_fields": {
  65. "total_goals": {
  66. "script": {
  67. "lang": "painless",
  68. "source": "int total = 0; for (int i = 0; i < doc['goals'].length; ++i) { total += doc['goals'][i]; } return total;"
  69. }
  70. }
  71. }
  72. }
  73. ----------------------------------------------------------------
  74. // CONSOLE
  75. The following example uses a Painless script to sort the players by their combined first and last names. The names are accessed using
  76. `doc['first'].value` and `doc['last'].value`.
  77. [source,js]
  78. ----------------------------------------------------------------
  79. GET hockey/_search
  80. {
  81. "query": {
  82. "match_all": {}
  83. },
  84. "sort": {
  85. "_script": {
  86. "type": "string",
  87. "order": "asc",
  88. "script": {
  89. "lang": "painless",
  90. "source": "doc['first.keyword'].value + ' ' + doc['last.keyword'].value"
  91. }
  92. }
  93. }
  94. }
  95. ----------------------------------------------------------------
  96. // CONSOLE
  97. [float]
  98. ==== Updating Fields with Painless
  99. You can also easily update fields. You access the original source for a field as `ctx._source.<field-name>`.
  100. First, let's look at the source data for a player by submitting the following request:
  101. [source,js]
  102. ----------------------------------------------------------------
  103. GET hockey/_search
  104. {
  105. "stored_fields": [
  106. "_id",
  107. "_source"
  108. ],
  109. "query": {
  110. "term": {
  111. "_id": 1
  112. }
  113. }
  114. }
  115. ----------------------------------------------------------------
  116. // CONSOLE
  117. To change player 1's last name to `hockey`, simply set `ctx._source.last` to the new value:
  118. [source,js]
  119. ----------------------------------------------------------------
  120. POST hockey/player/1/_update
  121. {
  122. "script": {
  123. "lang": "painless",
  124. "source": "ctx._source.last = params.last",
  125. "params": {
  126. "last": "hockey"
  127. }
  128. }
  129. }
  130. ----------------------------------------------------------------
  131. // CONSOLE
  132. You can also add fields to a document. For example, this script adds a new field that contains
  133. the player's nickname, _hockey_.
  134. [source,js]
  135. ----------------------------------------------------------------
  136. POST hockey/player/1/_update
  137. {
  138. "script": {
  139. "lang": "painless",
  140. "source": "ctx._source.last = params.last; ctx._source.nick = params.nick",
  141. "params": {
  142. "last": "gaudreau",
  143. "nick": "hockey"
  144. }
  145. }
  146. }
  147. ----------------------------------------------------------------
  148. // CONSOLE
  149. [float]
  150. [[modules-scripting-painless-dates]]
  151. ==== Dates
  152. Date fields are exposed as
  153. `ReadableDateTime`
  154. so they support methods like
  155. `getYear`,
  156. and `getDayOfWeek`.
  157. To get milliseconds since epoch call
  158. `getMillis`.
  159. For example, the following returns every hockey player's birth year:
  160. [source,js]
  161. ----------------------------------------------------------------
  162. GET hockey/_search
  163. {
  164. "script_fields": {
  165. "birth_year": {
  166. "script": {
  167. "source": "doc.born.value.year"
  168. }
  169. }
  170. }
  171. }
  172. ----------------------------------------------------------------
  173. // CONSOLE
  174. [float]
  175. [[modules-scripting-painless-regex]]
  176. ==== Regular expressions
  177. NOTE: Regexes are disabled by default because they circumvent Painless's
  178. protection against long running and memory hungry scripts. To make matters
  179. worse even innocuous looking regexes can have staggering performance and stack
  180. depth behavior. They remain an amazing powerful tool but are too scary to enable
  181. by default. To enable them yourself set `script.painless.regex.enabled: true` in
  182. `elasticsearch.yml`. We'd like very much to have a safe alternative
  183. implementation that can be enabled by default so check this space for later
  184. developments!
  185. Painless's native support for regular expressions has syntax constructs:
  186. * `/pattern/`: Pattern literals create patterns. This is the only way to create
  187. a pattern in painless. The pattern inside the ++/++'s are just
  188. http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html[Java regular expressions].
  189. See <<pattern-flags>> for more.
  190. * `=~`: The find operator return a `boolean`, `true` if a subsequence of the
  191. text matches, `false` otherwise.
  192. * `==~`: The match operator returns a `boolean`, `true` if the text matches,
  193. `false` if it doesn't.
  194. Using the find operator (`=~`) you can update all hockey players with "b" in
  195. their last name:
  196. [source,js]
  197. ----------------------------------------------------------------
  198. POST hockey/player/_update_by_query
  199. {
  200. "script": {
  201. "lang": "painless",
  202. "source": "if (ctx._source.last =~ /b/) {ctx._source.last += \"matched\"} else {ctx.op = 'noop'}"
  203. }
  204. }
  205. ----------------------------------------------------------------
  206. // CONSOLE
  207. Using the match operator (`==~`) you can update all the hockey players whose
  208. names start with a consonant and end with a vowel:
  209. [source,js]
  210. ----------------------------------------------------------------
  211. POST hockey/player/_update_by_query
  212. {
  213. "script": {
  214. "lang": "painless",
  215. "source": "if (ctx._source.last ==~ /[^aeiou].*[aeiou]/) {ctx._source.last += \"matched\"} else {ctx.op = 'noop'}"
  216. }
  217. }
  218. ----------------------------------------------------------------
  219. // CONSOLE
  220. You can use the `Pattern.matcher` directly to get a `Matcher` instance and
  221. remove all of the vowels in all of their last names:
  222. [source,js]
  223. ----------------------------------------------------------------
  224. POST hockey/player/_update_by_query
  225. {
  226. "script": {
  227. "lang": "painless",
  228. "source": "ctx._source.last = /[aeiou]/.matcher(ctx._source.last).replaceAll('')"
  229. }
  230. }
  231. ----------------------------------------------------------------
  232. // CONSOLE
  233. `Matcher.replaceAll` is just a call to Java's `Matcher`'s
  234. http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#replaceAll-java.lang.String-[replaceAll]
  235. method so it supports `$1` and `\1` for replacements:
  236. [source,js]
  237. ----------------------------------------------------------------
  238. POST hockey/player/_update_by_query
  239. {
  240. "script": {
  241. "lang": "painless",
  242. "source": "ctx._source.last = /n([aeiou])/.matcher(ctx._source.last).replaceAll('$1')"
  243. }
  244. }
  245. ----------------------------------------------------------------
  246. // CONSOLE
  247. If you need more control over replacements you can call `replaceAll` on a
  248. `CharSequence` with a `Function<Matcher, String>` that builds the replacement.
  249. This does not support `$1` or `\1` to access replacements because you already
  250. have a reference to the matcher and can get them with `m.group(1)`.
  251. IMPORTANT: Calling `Matcher.find` inside of the function that builds the
  252. replacement is rude and will likely break the replacement process.
  253. This will make all of the vowels in the hockey player's last names upper case:
  254. [source,js]
  255. ----------------------------------------------------------------
  256. POST hockey/player/_update_by_query
  257. {
  258. "script": {
  259. "lang": "painless",
  260. "source": "ctx._source.last = ctx._source.last.replaceAll(/[aeiou]/, m -> m.group().toUpperCase(Locale.ROOT))"
  261. }
  262. }
  263. ----------------------------------------------------------------
  264. // CONSOLE
  265. Or you can use the `CharSequence.replaceFirst` to make the first vowel in their
  266. last names upper case:
  267. [source,js]
  268. ----------------------------------------------------------------
  269. POST hockey/player/_update_by_query
  270. {
  271. "script": {
  272. "lang": "painless",
  273. "source": "ctx._source.last = ctx._source.last.replaceFirst(/[aeiou]/, m -> m.group().toUpperCase(Locale.ROOT))"
  274. }
  275. }
  276. ----------------------------------------------------------------
  277. // CONSOLE
  278. Note: all of the `_update_by_query` examples above could really do with a
  279. `query` to limit the data that they pull back. While you *could* use a
  280. {ref}/query-dsl-script-query.html[script query] it wouldn't be as efficient
  281. as using any other query because script queries aren't able to use the inverted
  282. index to limit the documents that they have to check.
  283. [[modules-scripting-painless-dispatch]]
  284. === How painless dispatches functions
  285. Painless uses receiver, name, and https://en.wikipedia.org/wiki/Arity[arity]
  286. for method dispatch. For example, `s.foo(a, b)` is resolved by first getting
  287. the class of `s` and then looking up the method `foo` with two parameters. This
  288. is different from Groovy which uses the
  289. https://en.wikipedia.org/wiki/Multiple_dispatch[runtime types] of the
  290. parameters and Java which uses the compile time types of the parameters.
  291. The consequence of this that Painless doesn't support overloaded methods like
  292. Java, leading to some trouble when it whitelists classes from the Java
  293. standard library. For example, in Java and Groovy, `Matcher` has two methods:
  294. `group(int)` and `group(String)`. Painless can't whitelist both of these methods
  295. because they have the same name and the same number of parameters. So instead it
  296. has `group(int)` and `namedGroup(String)`.
  297. We have a few justifications for this different way of dispatching methods:
  298. 1. It makes operating on `def` types simpler and, presumably, faster. Using
  299. receiver, name, and arity means that when Painless sees a call on a `def` object it
  300. can dispatch the appropriate method without having to do expensive comparisons
  301. of the types of the parameters. The same is true for invocations with `def`
  302. typed parameters.
  303. 2. It keeps things consistent. It would be genuinely weird for Painless to
  304. behave like Groovy if any `def` typed parameters were involved and Java
  305. otherwise. It'd be slow for it to behave like Groovy all the time.
  306. 3. It keeps Painless maintainable. Adding the Java or Groovy like method
  307. dispatch *feels* like it'd add a ton of complexity which'd make maintenance and
  308. other improvements much more difficult.
  309. include::painless-debugging.asciidoc[]