scripting.asciidoc 19 KB

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