scripting.asciidoc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. [[modules-scripting]]
  2. == Scripting
  3. The scripting module allows to use scripts in order to evaluate custom
  4. expressions. For example, scripts can be used to return "script fields"
  5. as part of a search request, or can be used to evaluate a custom score
  6. for a query and so on.
  7. The scripting module uses by default http://groovy.codehaus.org/[groovy]
  8. (previously http://mvel.codehaus.org/[mvel] in 1.3.x and earlier) as the
  9. scripting language with some extensions. Groovy is used since it is extremely
  10. fast and very simple to use.
  11. .Groovy dynamic scripting off by default from v1.4.3
  12. [IMPORTANT]
  13. ===================================================
  14. Groovy dynamic scripting is off by default, preventing dynamic Groovy scripts
  15. from being accepted as part of a request or retrieved from the special
  16. `.scripts` index. You will still be able to use Groovy scripts stored in files
  17. in the `config/scripts/` directory on every node.
  18. To convert an inline script to a file, take this simple script
  19. as an example:
  20. [source,json]
  21. -----------------------------------
  22. GET /_search
  23. {
  24. "script_fields": {
  25. "my_field": {
  26. "script": "1 + my_var",
  27. "params": {
  28. "my_var": 2
  29. }
  30. }
  31. }
  32. }
  33. -----------------------------------
  34. Save the contents of the script as a file called `config/scripts/my_script.groovy`
  35. on every data node in the cluster:
  36. [source,js]
  37. -----------------------------------
  38. 1 + my_var
  39. -----------------------------------
  40. Now you can access the script by file name (without the extension):
  41. [source,json]
  42. -----------------------------------
  43. GET /_search
  44. {
  45. "script_fields": {
  46. "my_field": {
  47. "script_file": "my_script",
  48. "params": {
  49. "my_var": 2
  50. }
  51. }
  52. }
  53. }
  54. -----------------------------------
  55. ===================================================
  56. Additional `lang` plugins are provided to allow to execute scripts in
  57. different languages. All places where a `script` parameter can be used, a `lang` parameter
  58. (on the same level) can be provided to define the language of the
  59. script. The following are the supported scripting languages:
  60. [cols="<,<,<",options="header",]
  61. |=======================================================================
  62. |Language |Sandboxed |Required plugin
  63. |groovy |no |built-in
  64. |expression |yes |built-in
  65. |mustache |yes |built-in
  66. |mvel |no |https://github.com/elastic/elasticsearch-lang-mvel[elasticsearch-lang-mvel]
  67. |javascript |no |https://github.com/elastic/elasticsearch-lang-javascript[elasticsearch-lang-javascript]
  68. |python |no |https://github.com/elastic/elasticsearch-lang-python[elasticsearch-lang-python]
  69. |=======================================================================
  70. To increase security, Elasticsearch does not allow you to specify scripts for
  71. non-sandboxed languages with a request. Instead, scripts must be placed in the
  72. `scripts` directory inside the configuration directory (the directory where
  73. elasticsearch.yml is). Scripts placed into this directory will automatically be
  74. picked up and be available to be used. Once a script has been placed in this
  75. directory, it can be referenced by name. For example, a script called
  76. `calculate-score.groovy` can be referenced in a request like this:
  77. [source,sh]
  78. --------------------------------------------------
  79. $ tree config
  80. config
  81. ├── elasticsearch.yml
  82. ├── logging.yml
  83. └── scripts
  84. └── calculate-score.groovy
  85. --------------------------------------------------
  86. [source,sh]
  87. --------------------------------------------------
  88. $ cat config/scripts/calculate-score.groovy
  89. log(_score * 2) + my_modifier
  90. --------------------------------------------------
  91. [source,js]
  92. --------------------------------------------------
  93. curl -XPOST localhost:9200/_search -d '{
  94. "query": {
  95. "function_score": {
  96. "query": {
  97. "match": {
  98. "body": "foo"
  99. }
  100. },
  101. "functions": [
  102. {
  103. "script_score": {
  104. "lang": "groovy",
  105. "script_file": "calculate-score",
  106. "params": {
  107. "my_modifier": 8
  108. }
  109. }
  110. }
  111. ]
  112. }
  113. }
  114. }'
  115. --------------------------------------------------
  116. The name of the script is derived from the hierarchy of directories it
  117. exists under, and the file name without the lang extension. For example,
  118. a script placed under `config/scripts/group1/group2/test.py` will be
  119. named `group1_group2_test`.
  120. [float]
  121. === Indexed Scripts
  122. Elasticsearch allows you to store scripts in an internal index known as
  123. `.scripts` and reference them by id. There are REST endpoints to manage
  124. indexed scripts as follows:
  125. Requests to the scripts endpoint look like :
  126. [source,js]
  127. -----------------------------------
  128. /_scripts/{lang}/{id}
  129. -----------------------------------
  130. Where the `lang` part is the language the script is in and the `id` part is the id
  131. of the script. In the `.scripts` index the type of the document will be set to the `lang`.
  132. [source,js]
  133. -----------------------------------
  134. curl -XPOST localhost:9200/_scripts/groovy/indexedCalculateScore -d '{
  135. "script": "log(_score * 2) + my_modifier"
  136. }'
  137. -----------------------------------
  138. This will create a document with id: `indexedCalculateScore` and type: `groovy` in the
  139. `.scripts` index. The type of the document is the language used by the script.
  140. This script can be accessed at query time by appending `_id` to
  141. the script parameter and passing the script id. So `script` becomes `script_id`.:
  142. [source,js]
  143. --------------------------------------------------
  144. curl -XPOST localhost:9200/_search -d '{
  145. "query": {
  146. "function_score": {
  147. "query": {
  148. "match": {
  149. "body": "foo"
  150. }
  151. },
  152. "functions": [
  153. {
  154. "script_score": {
  155. "script_id": "indexedCalculateScore",
  156. "lang" : "groovy",
  157. "params": {
  158. "my_modifier": 8
  159. }
  160. }
  161. }
  162. ]
  163. }
  164. }
  165. }'
  166. --------------------------------------------------
  167. The script can be viewed by:
  168. [source,js]
  169. -----------------------------------
  170. curl -XGET localhost:9200/_scripts/groovy/indexedCalculateScore
  171. -----------------------------------
  172. This is rendered as:
  173. [source,js]
  174. -----------------------------------
  175. '{
  176. "script": "log(_score * 2) + my_modifier"
  177. }'
  178. -----------------------------------
  179. Indexed scripts can be deleted by:
  180. [source,js]
  181. -----------------------------------
  182. curl -XDELETE localhost:9200/_scripts/groovy/indexedCalculateScore
  183. -----------------------------------
  184. [float]
  185. [[enable-dynamic-scripting]]
  186. === Enabling dynamic scripting
  187. We recommend running Elasticsearch behind an application or proxy, which
  188. protects Elasticsearch from the outside world. If users are allowed to run
  189. inline scripts (even in a search request) or indexed scripts, then they have
  190. the same access to your box as the user that Elasticsearch is running as. For
  191. this reason dynamic scripting is allowed only for sandboxed languages by default.
  192. First, you should not run Elasticsearch as the `root` user, as this would allow
  193. a script to access or do *anything* on your server, without limitations. Second,
  194. you should not expose Elasticsearch directly to users, but instead have a proxy
  195. application inbetween. If you *do* intend to expose Elasticsearch directly to
  196. your users, then you have to decide whether you trust them enough to run scripts
  197. on your box or not.
  198. It is possible to enable scripts based on their source, for
  199. every script engine, through the following settings that need to be added to the
  200. `config/elasticsearch.yml` file on every node.
  201. [source,yaml]
  202. -----------------------------------
  203. script.inline: on
  204. script.indexed: on
  205. -----------------------------------
  206. While this still allows execution of named scripts provided in the config, or
  207. _native_ Java scripts registered through plugins, it also allows users to run
  208. arbitrary scripts via the API. Instead of sending the name of the file as the
  209. script, the body of the script can be sent instead or retrieved from the
  210. `.scripts` indexed if previously stored.
  211. There are three possible configuration values for any of the fine-grained
  212. script settings:
  213. [cols="<,<",options="header",]
  214. |=======================================================================
  215. |Value |Description
  216. | `off` |scripting is turned off completely, in the context of the setting being set.
  217. | `on` |scripting is turned on, in the context of the setting being set.
  218. | `sandbox` |scripts may be executed only for languages that are sandboxed
  219. |=======================================================================
  220. The default values are the following:
  221. [source,yaml]
  222. -----------------------------------
  223. script.inline: sandbox
  224. script.indexed: sandbox
  225. script.file: on
  226. -----------------------------------
  227. NOTE: Global scripting settings affect the `mustache` scripting language.
  228. <<search-template,Search templates>> internally use the `mustache` language,
  229. and will still be enabled by default as the `mustache` engine is sandboxed,
  230. but they will be enabled/disabled according to fine-grained settings
  231. specified in `elasticsearch.yml`.
  232. It is also possible to control which operations can execute scripts. The
  233. supported operations are:
  234. [cols="<,<",options="header",]
  235. |=======================================================================
  236. |Value |Description
  237. | `aggs` |Aggregations (wherever they may be used)
  238. | `mapping` |Mappings (script transform feature)
  239. | `search` |Search api, Percolator api and Suggester api (e.g filters, script_fields)
  240. | `update` |Update api
  241. | `plugin` |Any plugin that makes use of scripts under the generic `plugin` category
  242. |=======================================================================
  243. Plugins can also define custom operations that they use scripts for instead
  244. of using the generic `plugin` category. Those operations can be referred to
  245. in the following form: `${pluginName}_${operation}`.
  246. The following example disables scripting for `update` and `mapping` operations,
  247. regardless of the script source, for any engine. Scripts can still be
  248. executed from sandboxed languages as part of `aggregations`, `search`
  249. and plugins execution though, as the above defaults still get applied.
  250. [source,yaml]
  251. -----------------------------------
  252. script.update: off
  253. script.mapping: off
  254. -----------------------------------
  255. Generic settings get applied in order, operation based ones have precedence
  256. over source based ones. Language specific settings are supported too. They
  257. need to be prefixed with the `script.engine.<engine>` prefix and have
  258. precedence over any other generic settings.
  259. [source,yaml]
  260. -----------------------------------
  261. script.engine.groovy.file.aggs: on
  262. script.engine.groovy.file.mapping: on
  263. script.engine.groovy.file.search: on
  264. script.engine.groovy.file.update: on
  265. script.engine.groovy.file.plugin: on
  266. script.engine.groovy.indexed.aggs: on
  267. script.engine.groovy.indexed.mapping: off
  268. script.engine.groovy.indexed.search: on
  269. script.engine.groovy.indexed.update: off
  270. script.engine.groovy.indexed.plugin: off
  271. script.engine.groovy.inline.aggs: on
  272. script.engine.groovy.inline.mapping: off
  273. script.engine.groovy.inline.search: off
  274. script.engine.groovy.inline.update: off
  275. script.engine.groovy.inline.plugin: off
  276. -----------------------------------
  277. [float]
  278. === Default Scripting Language
  279. The default scripting language (assuming no `lang` parameter is provided) is
  280. `groovy`. In order to change it, set the `script.default_lang` to the
  281. appropriate language.
  282. [float]
  283. === Automatic Script Reloading
  284. The `config/scripts` directory is scanned periodically for changes.
  285. New and changed scripts are reloaded and deleted script are removed
  286. from preloaded scripts cache. The reload frequency can be specified
  287. using `watcher.interval` setting, which defaults to `60s`.
  288. To disable script reloading completely set `script.auto_reload_enabled`
  289. to `false`.
  290. [[native-java-scripts]]
  291. [float]
  292. === Native (Java) Scripts
  293. Even though `groovy` is pretty fast, this allows to register native Java based
  294. scripts for faster execution.
  295. In order to allow for scripts, the `NativeScriptFactory` needs to be
  296. implemented that constructs the script that will be executed. There are
  297. two main types, one that extends `AbstractExecutableScript` and one that
  298. extends `AbstractSearchScript` (probably the one most users will extend,
  299. with additional helper classes in `AbstractLongSearchScript`,
  300. `AbstractDoubleSearchScript`, and `AbstractFloatSearchScript`).
  301. Registering them can either be done by settings, for example:
  302. `script.native.my.type` set to `sample.MyNativeScriptFactory` will
  303. register a script named `my`. Another option is in a plugin, access
  304. `ScriptModule` and call `registerScript` on it.
  305. Executing the script is done by specifying the `lang` as `native`, and
  306. the name of the script as the `script`.
  307. Note, the scripts need to be in the classpath of elasticsearch. One
  308. simple way to do it is to create a directory under plugins (choose a
  309. descriptive name), and place the jar / classes files there. They will be
  310. automatically loaded.
  311. [float]
  312. === Lucene Expressions Scripts
  313. experimental[The Lucene expressions module is undergoing significant development and the exposed functionality is likely to change in the future]
  314. Lucene's expressions module provides a mechanism to compile a
  315. `javascript` expression to bytecode. This allows very fast execution,
  316. as if you had written a `native` script. Expression scripts can be
  317. used in `script_score`, `script_fields`, sort scripts and numeric aggregation scripts.
  318. See the link:http://lucene.apache.org/core/4_9_0/expressions/index.html?org/apache/lucene/expressions/js/package-summary.html[expressions module documentation]
  319. for details on what operators and functions are available.
  320. Variables in `expression` scripts are available to access:
  321. * Single valued document fields, e.g. `doc['myfield'].value`
  322. * Parameters passed into the script, e.g. `mymodifier`
  323. * The current document's score, `_score` (only available when used in a `script_score`)
  324. There are a few limitations relative to other script languages:
  325. * Only numeric fields may be accessed
  326. * Stored fields are not available
  327. * If a field is sparse (only some documents contain a value), documents missing the field will have a value of `0`
  328. [float]
  329. === Score
  330. In all scripts that can be used in aggregations, the current
  331. document's score is accessible in `_score`.
  332. [float]
  333. === Computing scores based on terms in scripts
  334. see <<modules-advanced-scripting, advanced scripting documentation>>
  335. [float]
  336. === Document Fields
  337. Most scripting revolve around the use of specific document fields data.
  338. The `doc['field_name']` can be used to access specific field data within
  339. a document (the document in question is usually derived by the context
  340. the script is used). Document fields are very fast to access since they
  341. end up being loaded into memory (all the relevant field values/tokens
  342. are loaded to memory). Note, however, that the `doc[...]` notation only
  343. allows for simple valued fields (can’t return a json object from it)
  344. and makes sense only on non-analyzed or single term based fields.
  345. The following data can be extracted from a field:
  346. [cols="<,<",options="header",]
  347. |=======================================================================
  348. |Expression |Description
  349. |`doc['field_name'].value` |The native value of the field. For example,
  350. if its a short type, it will be short.
  351. |`doc['field_name'].values` |The native array values of the field. For
  352. example, if its a short type, it will be short[]. Remember, a field can
  353. have several values within a single doc. Returns an empty array if the
  354. field has no values.
  355. |`doc['field_name'].empty` |A boolean indicating if the field has no
  356. values within the doc.
  357. |`doc['field_name'].multiValued` |A boolean indicating that the field
  358. has several values within the corpus.
  359. |`doc['field_name'].lat` |The latitude of a geo point type.
  360. |`doc['field_name'].lon` |The longitude of a geo point type.
  361. |`doc['field_name'].lats` |The latitudes of a geo point type.
  362. |`doc['field_name'].lons` |The longitudes of a geo point type.
  363. |`doc['field_name'].distance(lat, lon)` |The `plane` distance (in meters)
  364. of this geo point field from the provided lat/lon.
  365. |`doc['field_name'].distanceWithDefault(lat, lon, default)` |The `plane` distance (in meters)
  366. of this geo point field from the provided lat/lon with a default value.
  367. |`doc['field_name'].distanceInMiles(lat, lon)` |The `plane` distance (in
  368. miles) of this geo point field from the provided lat/lon.
  369. |`doc['field_name'].distanceInMilesWithDefault(lat, lon, default)` |The `plane` distance (in
  370. miles) of this geo point field from the provided lat/lon with a default value.
  371. |`doc['field_name'].distanceInKm(lat, lon)` |The `plane` distance (in
  372. km) of this geo point field from the provided lat/lon.
  373. |`doc['field_name'].distanceInKmWithDefault(lat, lon, default)` |The `plane` distance (in
  374. km) of this geo point field from the provided lat/lon with a default value.
  375. |`doc['field_name'].arcDistance(lat, lon)` |The `arc` distance (in
  376. meters) of this geo point field from the provided lat/lon.
  377. |`doc['field_name'].arcDistanceWithDefault(lat, lon, default)` |The `arc` distance (in
  378. meters) of this geo point field from the provided lat/lon with a default value.
  379. |`doc['field_name'].arcDistanceInMiles(lat, lon)` |The `arc` distance (in
  380. miles) of this geo point field from the provided lat/lon.
  381. |`doc['field_name'].arcDistanceInMilesWithDefault(lat, lon, default)` |The `arc` distance (in
  382. miles) of this geo point field from the provided lat/lon with a default value.
  383. |`doc['field_name'].arcDistanceInKm(lat, lon)` |The `arc` distance (in
  384. km) of this geo point field from the provided lat/lon.
  385. |`doc['field_name'].arcDistanceInKmWithDefault(lat, lon, default)` |The `arc` distance (in
  386. km) of this geo point field from the provided lat/lon with a default value.
  387. |`doc['field_name'].factorDistance(lat, lon)` |The distance factor of this geo point field from the provided lat/lon.
  388. |`doc['field_name'].factorDistance(lat, lon, default)` |The distance factor of this geo point field from the provided lat/lon with a default value.
  389. |`doc['field_name'].geohashDistance(geohash)` |The `arc` distance (in meters)
  390. of this geo point field from the provided geohash.
  391. |`doc['field_name'].geohashDistanceInKm(geohash)` |The `arc` distance (in km)
  392. of this geo point field from the provided geohash.
  393. |`doc['field_name'].geohashDistanceInMiles(geohash)` |The `arc` distance (in
  394. miles) of this geo point field from the provided geohash.
  395. |=======================================================================
  396. [float]
  397. === Stored Fields
  398. Stored fields can also be accessed when executing a script. Note, they
  399. are much slower to access compared with document fields, as they are not
  400. loaded into memory. They can be simply accessed using
  401. `_fields['my_field_name'].value` or `_fields['my_field_name'].values`.
  402. [float]
  403. === Accessing the score of a document within a script
  404. When using scripting for calculating the score of a document (for instance, with
  405. the `function_score` query), you can access the score using the `_score`
  406. variable inside of a Groovy script.
  407. [float]
  408. === Source Field
  409. The source field can also be accessed when executing a script. The
  410. source field is loaded per doc, parsed, and then provided to the script
  411. for evaluation. The `_source` forms the context under which the source
  412. field can be accessed, for example `_source.obj2.obj1.field3`.
  413. Accessing `_source` is much slower compared to using `_doc`
  414. but the data is not loaded into memory. For a single field access `_fields` may be
  415. faster than using `_source` due to the extra overhead of potentially parsing large documents.
  416. However, `_source` may be faster if you access multiple fields or if the source has already been
  417. loaded for other purposes.
  418. [float]
  419. === Groovy Built In Functions
  420. There are several built in functions that can be used within scripts.
  421. They include:
  422. [cols="<,<",options="header",]
  423. |=======================================================================
  424. |Function |Description
  425. |`sin(a)` |Returns the trigonometric sine of an angle.
  426. |`cos(a)` |Returns the trigonometric cosine of an angle.
  427. |`tan(a)` |Returns the trigonometric tangent of an angle.
  428. |`asin(a)` |Returns the arc sine of a value.
  429. |`acos(a)` |Returns the arc cosine of a value.
  430. |`atan(a)` |Returns the arc tangent of a value.
  431. |`toRadians(angdeg)` |Converts an angle measured in degrees to an
  432. approximately equivalent angle measured in radians
  433. |`toDegrees(angrad)` |Converts an angle measured in radians to an
  434. approximately equivalent angle measured in degrees.
  435. |`exp(a)` |Returns Euler's number _e_ raised to the power of value.
  436. |`log(a)` |Returns the natural logarithm (base _e_) of a value.
  437. |`log10(a)` |Returns the base 10 logarithm of a value.
  438. |`sqrt(a)` |Returns the correctly rounded positive square root of a
  439. value.
  440. |`cbrt(a)` |Returns the cube root of a double value.
  441. |`IEEEremainder(f1, f2)` |Computes the remainder operation on two
  442. arguments as prescribed by the IEEE 754 standard.
  443. |`ceil(a)` |Returns the smallest (closest to negative infinity) value
  444. that is greater than or equal to the argument and is equal to a
  445. mathematical integer.
  446. |`floor(a)` |Returns the largest (closest to positive infinity) value
  447. that is less than or equal to the argument and is equal to a
  448. mathematical integer.
  449. |`rint(a)` |Returns the value that is closest in value to the argument
  450. and is equal to a mathematical integer.
  451. |`atan2(y, x)` |Returns the angle _theta_ from the conversion of
  452. rectangular coordinates (_x_, _y_) to polar coordinates (r,_theta_).
  453. |`pow(a, b)` |Returns the value of the first argument raised to the
  454. power of the second argument.
  455. |`round(a)` |Returns the closest _int_ to the argument.
  456. |`random()` |Returns a random _double_ value.
  457. |`abs(a)` |Returns the absolute value of a value.
  458. |`max(a, b)` |Returns the greater of two values.
  459. |`min(a, b)` |Returns the smaller of two values.
  460. |`ulp(d)` |Returns the size of an ulp of the argument.
  461. |`signum(d)` |Returns the signum function of the argument.
  462. |`sinh(x)` |Returns the hyperbolic sine of a value.
  463. |`cosh(x)` |Returns the hyperbolic cosine of a value.
  464. |`tanh(x)` |Returns the hyperbolic tangent of a value.
  465. |`hypot(x, y)` |Returns sqrt(_x2_ + _y2_) without intermediate overflow
  466. or underflow.
  467. |=======================================================================
  468. [float]
  469. === Arithmetic precision in MVEL
  470. When dividing two numbers using MVEL based scripts, the engine tries to
  471. be smart and adheres to the default behaviour of java. This means if you
  472. divide two integers (you might have configured the fields as integer in
  473. the mapping), the result will also be an integer. This means, if a
  474. calculation like `1/num` is happening in your scripts and `num` is an
  475. integer with the value of `8`, the result is `0` even though you were
  476. expecting it to be `0.125`. You may need to enforce precision by
  477. explicitly using a double like `1.0/num` in order to get the expected
  478. result.