scripting.asciidoc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. [[modules-scripting]]
  2. == Scripting
  3. The scripting module enables you to use scripts to evaluate custom
  4. expressions. For example, you could use a script to return "script fields"
  5. as part of a search request or evaluate a custom score for a query.
  6. TIP: Elasticsearch now has a built-in scripting language called _Painless_
  7. that provides a more secure alternative for implementing
  8. scripts for Elasticsearch. We encourage you to try it out--
  9. for more information, see <<modules-scripting-painless, Painless Scripting Language>>.
  10. The default scripting language is http://groovy-lang.org/[groovy]
  11. (http://mvel.codehaus.org/[mvel] was the default in 1.3.x and earlier).
  12. Additional `lang` plugins enable you to run scripts written in other languages.
  13. Everywhere a script can be used, you can include a `lang` parameter
  14. to specify the language of the script. Plugins are available for following languages:
  15. [cols="<,<,<",options="header",]
  16. |=======================================================================
  17. |Language |Sandboxed |Required plugin
  18. |groovy |no |built-in
  19. |expression |yes |built-in
  20. |mustache |yes |built-in
  21. |painless |yes |built-in (module)
  22. |javascript |no |{plugins}/lang-javascript.html[elasticsearch-lang-javascript]
  23. |python |no |{plugins}/lang-python.html[elasticsearch-lang-python]
  24. |=======================================================================
  25. .Groovy dynamic scripting off by default from v1.4.3
  26. [IMPORTANT]
  27. ===================================================
  28. Groovy dynamic scripting is off by default. This prevents Groovy scripts
  29. from being accepted as part of a request or retrieved from the
  30. `.scripts` index. You can still use Groovy file scripts stored in
  31. the `config/scripts/` directory on every node.
  32. To convert an inline script to a file-based script, save the contents
  33. of the `inline` field to a file with the `.groovy` extension and
  34. store it in the `config/scripts` directory on every data node in your
  35. cluster.
  36. For example, if you have the following inline script:
  37. [source,js]
  38. -----------------------------------
  39. GET /_search
  40. {
  41. "script_fields": {
  42. "my_field": {
  43. "inline": "1 + my_var",
  44. "params": {
  45. "my_var": 2
  46. }
  47. }
  48. }
  49. }
  50. -----------------------------------
  51. Save `1 + my_var` in a file called `config/scripts/my_script.groovy`.
  52. To use the script in a request, specify its name (without the `.groovy` extension) in the `file` field:
  53. [source,js]
  54. -----------------------------------
  55. GET /_search
  56. {
  57. "script_fields": {
  58. "my_field": {
  59. "script": {
  60. "file": "my_script",
  61. "params": {
  62. "my_var": 2
  63. }
  64. }
  65. }
  66. }
  67. }
  68. -----------------------------------
  69. ===================================================
  70. [float]
  71. === File-based Scripts
  72. To increase security, Elasticsearch does not allow you to specify scripts for
  73. non-sandboxed languages with a request. Instead, scripts must be placed in the
  74. `scripts` directory inside the configuration directory (the directory where
  75. elasticsearch.yml is). The default location of this `scripts` directory can be
  76. changed by setting `path.scripts` in elasticsearch.yml. Scripts placed into
  77. this directory will automatically be picked up and be available to be used.
  78. Once a script has been placed in this directory, it can be referenced by name.
  79. For example, a script called `calculate-score.groovy` can be referenced in a
  80. request like this:
  81. [source,sh]
  82. --------------------------------------------------
  83. $ tree config
  84. config
  85. ├── elasticsearch.yml
  86. ├── logging.yml
  87. └── scripts
  88. └── calculate-score.groovy
  89. --------------------------------------------------
  90. [source,sh]
  91. --------------------------------------------------
  92. $ cat config/scripts/calculate-score.groovy
  93. log(_score * 2) + my_modifier
  94. --------------------------------------------------
  95. [source,js]
  96. --------------------------------------------------
  97. curl -XPOST localhost:9200/_search -d '{
  98. "query": {
  99. "function_score": {
  100. "query": {
  101. "match": {
  102. "body": "foo"
  103. }
  104. },
  105. "functions": [
  106. {
  107. "script_score": {
  108. "script": {
  109. "lang": "groovy",
  110. "file": "calculate-score",
  111. "params": {
  112. "my_modifier": 8
  113. }
  114. }
  115. }
  116. }
  117. ]
  118. }
  119. }
  120. }'
  121. --------------------------------------------------
  122. The name of the script is derived from the hierarchy of directories it
  123. exists under, and the file name without the lang extension. For example,
  124. a script placed under `config/scripts/group1/group2/test.py` will be
  125. named `group1_group2_test`.
  126. [float]
  127. [[modules-scripting-stored-scripts]]
  128. === Stored Scripts
  129. Elasticsearch allows you to store scripts in the cluster state.
  130. There are REST endpoints to manage stored scripts as follows:
  131. Requests to the scripts endpoint look like :
  132. [source,js]
  133. -----------------------------------
  134. /_scripts/{lang}/{id}
  135. -----------------------------------
  136. Where the `lang` part is the language the script is in and the `id` part is the id
  137. of the script.
  138. [source,js]
  139. -----------------------------------
  140. curl -XPOST localhost:9200/_scripts/groovy/calculateScore -d '{
  141. "script": "log(_score * 2) + my_modifier"
  142. }'
  143. -----------------------------------
  144. This will store the script under the `calculateScore` in the cluster
  145. state.
  146. This script can be accessed at query time by using the `id` and `lang` script parameters:
  147. [source,js]
  148. --------------------------------------------------
  149. curl -XPOST localhost:9200/_search -d '{
  150. "query": {
  151. "function_score": {
  152. "query": {
  153. "match": {
  154. "body": "foo"
  155. }
  156. },
  157. "functions": [
  158. {
  159. "script_score": {
  160. "script": {
  161. "id": "calculateScore",
  162. "lang" : "groovy",
  163. "params": {
  164. "my_modifier": 8
  165. }
  166. }
  167. }
  168. }
  169. ]
  170. }
  171. }
  172. }'
  173. --------------------------------------------------
  174. The script can be viewed by:
  175. [source,js]
  176. -----------------------------------
  177. curl -XGET localhost:9200/_scripts/groovy/calculateScore
  178. -----------------------------------
  179. This is rendered as:
  180. [source,js]
  181. -----------------------------------
  182. '{
  183. "script": "log(_score * 2) + my_modifier"
  184. }'
  185. -----------------------------------
  186. Stored scripts can be deleted by:
  187. [source,js]
  188. -----------------------------------
  189. curl -XDELETE localhost:9200/_scripts/groovy/calculateScore
  190. -----------------------------------
  191. NOTE: The size of stored scripts is limited to 65535 bytes. This can be changed by setting `script.max_size_in_bytes`
  192. setting to increase that soft limit, but if scripts are really large then alternatives like native scripts should be considered.
  193. [float]
  194. [[enable-dynamic-scripting]]
  195. === Enabling dynamic scripting
  196. We recommend running Elasticsearch behind an application or proxy, which
  197. protects Elasticsearch from the outside world. If users are allowed to run
  198. inline scripts (even in a search request) or indexed scripts, then they have
  199. the same access to your box as the user that Elasticsearch is running as. For
  200. this reason dynamic scripting is allowed only for sandboxed languages by default.
  201. First, you should not run Elasticsearch as the `root` user, as this would allow
  202. a script to access or do *anything* on your server, without limitations. Second,
  203. you should not expose Elasticsearch directly to users, but instead have a proxy
  204. application inbetween. If you *do* intend to expose Elasticsearch directly to
  205. your users, then you have to decide whether you trust them enough to run scripts
  206. on your box or not.
  207. It is possible to enable scripts based on their source, for
  208. every script engine, through the following settings that need to be added to the
  209. `config/elasticsearch.yml` file on every node.
  210. [source,yaml]
  211. -----------------------------------
  212. script.inline: true
  213. script.stored: true
  214. -----------------------------------
  215. While this still allows execution of named scripts provided in the config, or
  216. _native_ Java scripts registered through plugins, it also allows users to run
  217. arbitrary scripts via the API. Instead of sending the name of the file as the
  218. script, the body of the script can be sent instead or retrieved from the
  219. cluster state if previously stored.
  220. There are three possible configuration values for any of the fine-grained
  221. script settings:
  222. [cols="<,<",options="header",]
  223. |=======================================================================
  224. |Value |Description
  225. | `false` |scripting is turned off completely, in the context of the setting being set.
  226. | `true` |scripting is turned on, in the context of the setting being set.
  227. | `sandbox` |scripts may be executed only for languages that are sandboxed
  228. |=======================================================================
  229. The default values are the following:
  230. [source,yaml]
  231. -----------------------------------
  232. script.inline: sandbox
  233. script.stored: sandbox
  234. script.file: true
  235. -----------------------------------
  236. NOTE: Global scripting settings affect the `mustache` scripting language.
  237. <<search-template,Search templates>> internally use the `mustache` language,
  238. and will still be enabled by default as the `mustache` engine is sandboxed,
  239. but they will be enabled/disabled according to fine-grained settings
  240. specified in `elasticsearch.yml`.
  241. It is also possible to control which operations can execute scripts. The
  242. supported operations are:
  243. [cols="<,<",options="header",]
  244. |=======================================================================
  245. |Value |Description
  246. | `aggs` |Aggregations (wherever they may be used)
  247. | `search` |Search api, Percolator api and Suggester api (e.g filters, script_fields)
  248. | `update` |Update api
  249. | `plugin` |Any plugin that makes use of scripts under the generic `plugin` category
  250. |=======================================================================
  251. Plugins can also define custom operations that they use scripts for instead
  252. of using the generic `plugin` category. Those operations can be referred to
  253. in the following form: `${pluginName}_${operation}`.
  254. The following example disables scripting for `update` and `mapping` operations,
  255. regardless of the script source, for any engine. Scripts can still be
  256. executed from sandboxed languages as part of `aggregations`, `search`
  257. and plugins execution though, as the above defaults still get applied.
  258. [source,yaml]
  259. -----------------------------------
  260. script.update: false
  261. script.mapping: false
  262. -----------------------------------
  263. Generic settings get applied in order, operation based ones have precedence
  264. over source based ones. Language specific settings are supported too. They
  265. need to be prefixed with the `script.engine.<engine>` prefix and have
  266. precedence over any other generic settings.
  267. [source,yaml]
  268. -----------------------------------
  269. script.engine.groovy.file.aggs: true
  270. script.engine.groovy.file.mapping: true
  271. script.engine.groovy.file.search: true
  272. script.engine.groovy.file.update: true
  273. script.engine.groovy.file.plugin: true
  274. script.engine.groovy.stored.aggs: true
  275. script.engine.groovy.stored.mapping: false
  276. script.engine.groovy.stored.search: true
  277. script.engine.groovy.stored.update: false
  278. script.engine.groovy.stored.plugin: false
  279. script.engine.groovy.inline.aggs: true
  280. script.engine.groovy.inline.mapping: false
  281. script.engine.groovy.inline.search: false
  282. script.engine.groovy.inline.update: false
  283. script.engine.groovy.inline.plugin: false
  284. -----------------------------------
  285. [float]
  286. === Default Scripting Language
  287. The default scripting language (assuming no `lang` parameter is provided) is
  288. `groovy`. In order to change it, set the `script.default_lang` to the
  289. appropriate language.
  290. [float]
  291. === Automatic Script Reloading
  292. The `config/scripts` directory is scanned periodically for changes.
  293. New and changed scripts are reloaded and deleted script are removed
  294. from preloaded scripts cache. The reload frequency can be specified
  295. using `resource.reload.interval` setting, which defaults to `60s`.
  296. To disable script reloading completely set `script.auto_reload_enabled`
  297. to `false`.
  298. [[native-java-scripts]]
  299. [float]
  300. === Native (Java) Scripts
  301. Sometimes `groovy` and `expressions` aren't enough. For those times you can
  302. implement a native script.
  303. The best way to implement a native script is to write a plugin and install it.
  304. The plugin {plugins}/plugin-authors.html[documentation] has more information on
  305. how to write a plugin so that Elasticsearch will properly load it.
  306. To register the actual script you'll need to implement `NativeScriptFactory`
  307. to construct the script. The actual script will extend either
  308. `AbstractExecutableScript` or `AbstractSearchScript`. The second one is likely
  309. the most useful and has several helpful subclasses you can extend like
  310. `AbstractLongSearchScript`, `AbstractDoubleSearchScript`, and
  311. `AbstractFloatSearchScript`. Finally, your plugin should register the native
  312. script by declaring the `onModule(ScriptModule)` method.
  313. If you squashed the whole thing into one class it'd look like:
  314. [source,java]
  315. --------------------------------------------------
  316. public class MyNativeScriptPlugin extends Plugin {
  317. @Override
  318. public String name() {
  319. return "my-native-script";
  320. }
  321. @Override
  322. public String description() {
  323. return "my native script that does something great";
  324. }
  325. public void onModule(ScriptModule scriptModule) {
  326. scriptModule.registerScript("my_script", MyNativeScriptFactory.class);
  327. }
  328. public static class MyNativeScriptFactory implements NativeScriptFactory {
  329. @Override
  330. public ExecutableScript newScript(@Nullable Map<String, Object> params) {
  331. return new MyNativeScript();
  332. }
  333. @Override
  334. public boolean needsScores() {
  335. return false;
  336. }
  337. }
  338. public static class MyNativeScript extends AbstractFloatSearchScript {
  339. @Override
  340. public float runAsFloat() {
  341. float a = (float) source().get("a");
  342. float b = (float) source().get("b");
  343. return a * b;
  344. }
  345. }
  346. }
  347. --------------------------------------------------
  348. You can execute the script by specifying its `lang` as `native`, and the name
  349. of the script as the `id`:
  350. [source,js]
  351. --------------------------------------------------
  352. curl -XPOST localhost:9200/_search -d '{
  353. "query": {
  354. "function_score": {
  355. "query": {
  356. "match": {
  357. "body": "foo"
  358. }
  359. },
  360. "functions": [
  361. {
  362. "script_score": {
  363. "script": {
  364. "id": "my_script",
  365. "lang" : "native"
  366. }
  367. }
  368. }
  369. ]
  370. }
  371. }
  372. }'
  373. --------------------------------------------------
  374. [float]
  375. === Lucene Expressions Scripts
  376. experimental[The Lucene expressions module is undergoing significant development and the exposed functionality is likely to change in the future]
  377. Lucene's expressions module provides a mechanism to compile a
  378. `javascript` expression to bytecode. This allows very fast execution,
  379. as if you had written a `native` script. Expression scripts can be
  380. used in `script_score`, `script_fields`, sort scripts and numeric aggregation scripts.
  381. 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]
  382. for details on what operators and functions are available.
  383. Variables in `expression` scripts are available to access:
  384. * document fields, e.g. `doc['myfield'].value`
  385. * variables and methods that the field supports, e.g. `doc['myfield'].empty`
  386. * Parameters passed into the script, e.g. `mymodifier`
  387. * The current document's score, `_score` (only available when used in a `script_score`)
  388. [float]
  389. === Expressions API for numeric fields
  390. [cols="<,<",options="header",]
  391. |=======================================================================
  392. |Expression |Description
  393. |`doc['field_name'].value` |The native value of the field. For example,
  394. if its a short type, it will be short.
  395. |`doc['field_name'].empty` |A boolean indicating if the field has no
  396. values within the doc.
  397. |`doc['field_name'].min()` |The minimum value of the field in this document.
  398. |`doc['field_name'].max()` |The maximum value of the field in this document.
  399. |`doc['field_name'].median()` |The median value of the field in this document.
  400. |`doc['field_name'].avg()` |The average of the values in this document.
  401. |`doc['field_name'].sum()` |The sum of the values in this document.
  402. |`doc['field_name'].count()` |The number of values in this document.
  403. |=======================================================================
  404. When a document is missing the field completely, by default the value will be treated as `0`.
  405. You can treat it as another value instead, e.g. `doc['myfield'].empty ? 100 : doc['myfield'].value`
  406. When a document has multiple values for the field, by default the minimum value is returned.
  407. You can choose a different value instead, e.g. `doc['myfield'].sum()`.
  408. When a document is missing the field completely, by default the value will be treated as `0`.
  409. Boolean fields are exposed as numerics, with `true` mapped to `1` and `false` mapped to `0`.
  410. For example: `doc['on_sale'] ? doc['price'] * 0.5 : doc['price']`
  411. [float]
  412. === Additional methods for date fields
  413. Date fields are treated as the number of milliseconds since January 1, 1970 and
  414. support the numeric API above, with these additional methods:
  415. [cols="<,<",options="header",]
  416. |=======================================================================
  417. |Expression |Description
  418. |`doc['field_name'].getYear()` |Year component, e.g. `1970`.
  419. |`doc['field_name'].getMonth()` |Month component (0-11), e.g. `0` for January.
  420. |`doc['field_name'].getDayOfMonth()` |Day component, e.g. `1` for the first of the month.
  421. |`doc['field_name'].getHourOfDay()` |Hour component (0-23)
  422. |`doc['field_name'].getMinutes()` |Minutes component (0-59)
  423. |`doc['field_name'].getSeconds()` |Seconds component (0-59)
  424. |=======================================================================
  425. The following example shows the difference in years between the `date` fields date0 and date1:
  426. `doc['date1'].getYear() - doc['date0'].getYear()`
  427. [float]
  428. === Expressions API for `geo_point` fields
  429. [cols="<,<",options="header",]
  430. |=======================================================================
  431. |Expression |Description
  432. |`doc['field_name'].empty` |A boolean indicating if the field has no
  433. values within the doc.
  434. |`doc['field_name'].lat` |The latitude of the geo point.
  435. |`doc['field_name'].lon` |The longitude of the geo point.
  436. |=======================================================================
  437. The following example computes distance in kilometers from Washington, DC:
  438. `haversin(38.9072, 77.0369, doc['field_name'].lat, doc['field_name'].lon)`
  439. In this example the coordinates could have been passed as parameters to the script,
  440. e.g. based on geolocation of the user.
  441. [float]
  442. === Expressions limitations
  443. There are a few limitations relative to other script languages:
  444. * Only numeric, boolean, date, and geo_point fields may be accessed
  445. * Stored fields are not available
  446. [float]
  447. === Score
  448. In all scripts that can be used in aggregations, the current
  449. document's score is accessible in `_score`.
  450. [float]
  451. === Computing scores based on terms in scripts
  452. see <<modules-advanced-scripting, advanced scripting documentation>>
  453. [float]
  454. === Document Fields
  455. Most scripting revolve around the use of specific document fields data.
  456. The `doc['field_name']` can be used to access specific field data within
  457. a document (the document in question is usually derived by the context
  458. the script is used). Document fields are very fast to access since they
  459. end up being loaded into memory (all the relevant field values/tokens
  460. are loaded to memory). Note, however, that the `doc[...]` notation only
  461. allows for simple valued fields (can’t return a json object from it)
  462. and makes sense only on non-analyzed or single term based fields.
  463. The following data can be extracted from a field:
  464. [cols="<,<",options="header",]
  465. |=======================================================================
  466. |Expression |Description
  467. |`doc['field_name'].value` |The native value of the field. For example,
  468. if its a short type, it will be short.
  469. |`doc['field_name'].values` |The native array values of the field. For
  470. example, if its a short type, it will be short[]. Remember, a field can
  471. have several values within a single doc. Returns an empty array if the
  472. field has no values.
  473. |`doc['field_name'].empty` |A boolean indicating if the field has no
  474. values within the doc.
  475. |`doc['field_name'].multiValued` |A boolean indicating that the field
  476. has several values within the corpus.
  477. |`doc['field_name'].lat` |The latitude of a geo point type.
  478. |`doc['field_name'].lon` |The longitude of a geo point type.
  479. |`doc['field_name'].lats` |The latitudes of a geo point type.
  480. |`doc['field_name'].lons` |The longitudes of a geo point type.
  481. |`doc['field_name'].distance(lat, lon)` |The `plane` distance (in meters)
  482. of this geo point field from the provided lat/lon.
  483. |`doc['field_name'].distanceWithDefault(lat, lon, default)` |The `plane` distance (in meters)
  484. of this geo point field from the provided lat/lon with a default value.
  485. |`doc['field_name'].distanceInMiles(lat, lon)` |The `plane` distance (in
  486. miles) of this geo point field from the provided lat/lon.
  487. |`doc['field_name'].distanceInMilesWithDefault(lat, lon, default)` |The `plane` distance (in
  488. miles) of this geo point field from the provided lat/lon with a default value.
  489. |`doc['field_name'].distanceInKm(lat, lon)` |The `plane` distance (in
  490. km) of this geo point field from the provided lat/lon.
  491. |`doc['field_name'].distanceInKmWithDefault(lat, lon, default)` |The `plane` distance (in
  492. km) of this geo point field from the provided lat/lon with a default value.
  493. |`doc['field_name'].arcDistance(lat, lon)` |The `arc` distance (in
  494. meters) of this geo point field from the provided lat/lon.
  495. |`doc['field_name'].arcDistanceWithDefault(lat, lon, default)` |The `arc` distance (in
  496. meters) of this geo point field from the provided lat/lon with a default value.
  497. |`doc['field_name'].arcDistanceInMiles(lat, lon)` |The `arc` distance (in
  498. miles) of this geo point field from the provided lat/lon.
  499. |`doc['field_name'].arcDistanceInMilesWithDefault(lat, lon, default)` |The `arc` distance (in
  500. miles) of this geo point field from the provided lat/lon with a default value.
  501. |`doc['field_name'].arcDistanceInKm(lat, lon)` |The `arc` distance (in
  502. km) of this geo point field from the provided lat/lon.
  503. |`doc['field_name'].arcDistanceInKmWithDefault(lat, lon, default)` |The `arc` distance (in
  504. km) of this geo point field from the provided lat/lon with a default value.
  505. |`doc['field_name'].factorDistance(lat, lon)` |The distance factor of this geo point field from the provided lat/lon.
  506. |`doc['field_name'].factorDistance(lat, lon, default)` |The distance factor of this geo point field from the provided lat/lon with a default value.
  507. |`doc['field_name'].geohashDistance(geohash)` |The `arc` distance (in meters)
  508. of this geo point field from the provided geohash.
  509. |`doc['field_name'].geohashDistanceInKm(geohash)` |The `arc` distance (in km)
  510. of this geo point field from the provided geohash.
  511. |`doc['field_name'].geohashDistanceInMiles(geohash)` |The `arc` distance (in
  512. miles) of this geo point field from the provided geohash.
  513. |=======================================================================
  514. [float]
  515. === Stored Fields
  516. Stored fields can also be accessed when executing a script. Note, they
  517. are much slower to access compared with document fields, as they are not
  518. loaded into memory. They can be simply accessed using
  519. `_fields['my_field_name'].value` or `_fields['my_field_name'].values`.
  520. [float]
  521. === Accessing the score of a document within a script
  522. When using scripting for calculating the score of a document (for instance, with
  523. the `function_score` query), you can access the score using the `_score`
  524. variable inside of a Groovy script.
  525. [float]
  526. === Source Field
  527. The source field can also be accessed when executing a script. The
  528. source field is loaded per doc, parsed, and then provided to the script
  529. for evaluation. The `_source` forms the context under which the source
  530. field can be accessed, for example `_source.obj2.obj1.field3`.
  531. Accessing `_source` is much slower compared to using `doc`
  532. but the data is not loaded into memory. For a single field access `_fields` may be
  533. faster than using `_source` due to the extra overhead of potentially parsing large documents.
  534. However, `_source` may be faster if you access multiple fields or if the source has already been
  535. loaded for other purposes.
  536. [float]
  537. === Groovy Built In Functions
  538. There are several built in functions that can be used within scripts.
  539. They include:
  540. [cols="<,<",options="header",]
  541. |=======================================================================
  542. |Function |Description
  543. |`sin(a)` |Returns the trigonometric sine of an angle.
  544. |`cos(a)` |Returns the trigonometric cosine of an angle.
  545. |`tan(a)` |Returns the trigonometric tangent of an angle.
  546. |`asin(a)` |Returns the arc sine of a value.
  547. |`acos(a)` |Returns the arc cosine of a value.
  548. |`atan(a)` |Returns the arc tangent of a value.
  549. |`toRadians(angdeg)` |Converts an angle measured in degrees to an
  550. approximately equivalent angle measured in radians
  551. |`toDegrees(angrad)` |Converts an angle measured in radians to an
  552. approximately equivalent angle measured in degrees.
  553. |`exp(a)` |Returns Euler's number _e_ raised to the power of value.
  554. |`log(a)` |Returns the natural logarithm (base _e_) of a value.
  555. |`log10(a)` |Returns the base 10 logarithm of a value.
  556. |`sqrt(a)` |Returns the correctly rounded positive square root of a
  557. value.
  558. |`cbrt(a)` |Returns the cube root of a double value.
  559. |`IEEEremainder(f1, f2)` |Computes the remainder operation on two
  560. arguments as prescribed by the IEEE 754 standard.
  561. |`ceil(a)` |Returns the smallest (closest to negative infinity) value
  562. that is greater than or equal to the argument and is equal to a
  563. mathematical integer.
  564. |`floor(a)` |Returns the largest (closest to positive infinity) value
  565. that is less than or equal to the argument and is equal to a
  566. mathematical integer.
  567. |`rint(a)` |Returns the value that is closest in value to the argument
  568. and is equal to a mathematical integer.
  569. |`atan2(y, x)` |Returns the angle _theta_ from the conversion of
  570. rectangular coordinates (_x_, _y_) to polar coordinates (r,_theta_).
  571. |`pow(a, b)` |Returns the value of the first argument raised to the
  572. power of the second argument.
  573. |`round(a)` |Returns the closest _int_ to the argument.
  574. |`random()` |Returns a random _double_ value.
  575. |`abs(a)` |Returns the absolute value of a value.
  576. |`max(a, b)` |Returns the greater of two values.
  577. |`min(a, b)` |Returns the smaller of two values.
  578. |`ulp(d)` |Returns the size of an ulp of the argument.
  579. |`signum(d)` |Returns the signum function of the argument.
  580. |`sinh(x)` |Returns the hyperbolic sine of a value.
  581. |`cosh(x)` |Returns the hyperbolic cosine of a value.
  582. |`tanh(x)` |Returns the hyperbolic tangent of a value.
  583. |`hypot(x, y)` |Returns sqrt(_x2_ + _y2_) without intermediate overflow
  584. or underflow.
  585. |=======================================================================