2018-07-02 17:44:36 -04:00
|
|
|
[[painless-field-context]]
|
|
|
|
=== Field context
|
|
|
|
|
|
|
|
Use a Painless script to create a
|
2019-07-19 09:16:35 -04:00
|
|
|
{ref}/search-request-body.html#request-body-search-script-fields[script field] to return
|
2018-07-02 17:44:36 -04:00
|
|
|
a customized value for each document in the results of a query.
|
|
|
|
|
|
|
|
*Variables*
|
|
|
|
|
|
|
|
`params` (`Map`, read-only)::
|
|
|
|
User-defined parameters passed in as part of the query.
|
|
|
|
|
|
|
|
`doc` (`Map`, read-only)::
|
|
|
|
Contains the fields of the specified document where each field is a
|
|
|
|
`List` of values.
|
|
|
|
|
2018-10-20 19:33:49 -04:00
|
|
|
{ref}/mapping-source-field.html[`params['_source']`] (`Map`, read-only)::
|
2018-07-02 17:44:36 -04:00
|
|
|
Contains extracted JSON in a `Map` and `List` structure for the fields
|
|
|
|
existing in a stored document.
|
|
|
|
|
|
|
|
*Return*
|
|
|
|
|
|
|
|
`Object`::
|
|
|
|
The customized value for each document.
|
|
|
|
|
|
|
|
*API*
|
|
|
|
|
2018-10-20 19:33:49 -04:00
|
|
|
The standard <<painless-api-reference, Painless API>> is available.
|
2018-11-08 14:54:20 -05:00
|
|
|
|
|
|
|
|
|
|
|
*Example*
|
|
|
|
|
|
|
|
To run this example, first follow the steps in
|
|
|
|
<<painless-context-examples, context examples>>.
|
|
|
|
|
|
|
|
You can then use these two example scripts to compute custom information
|
|
|
|
for each search hit and output it to two new fields.
|
|
|
|
|
|
|
|
The first script gets the doc value for the `datetime` field and calls
|
|
|
|
the `getDayOfWeek` function to determine the corresponding day of the week.
|
|
|
|
|
|
|
|
[source,Painless]
|
|
|
|
----
|
|
|
|
doc['datetime'].value.getDayOfWeek();
|
|
|
|
----
|
|
|
|
|
|
|
|
The second script calculates the number of actors. Actors' names are stored
|
|
|
|
as a text array in the `actors` field.
|
|
|
|
|
|
|
|
[source,Painless]
|
|
|
|
----
|
|
|
|
params['_source']['actors'].length; <1>
|
|
|
|
----
|
|
|
|
|
|
|
|
<1> By default, doc values are not available for text fields. However,
|
|
|
|
you can still calculate the number of actors by extracting actors
|
|
|
|
from `_source`. Note that `params['_source']['actors']` is a list.
|
|
|
|
|
|
|
|
|
|
|
|
Submit the following request:
|
|
|
|
|
|
|
|
[source,js]
|
|
|
|
----
|
|
|
|
GET seats/_search
|
|
|
|
{
|
|
|
|
"query" : {
|
|
|
|
"match_all": {}
|
|
|
|
},
|
|
|
|
"script_fields" : {
|
|
|
|
"day-of-week" : {
|
|
|
|
"script" : {
|
|
|
|
"source": "doc['datetime'].value.getDayOfWeek()"
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"number-of-actors" : {
|
|
|
|
"script" : {
|
|
|
|
"source": "params['_source']['actors'].length"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
// CONSOLE
|
|
|
|
// TEST[skip: requires setup from other pages]
|