84 lines
2.1 KiB
Plaintext
84 lines
2.1 KiB
Plaintext
[[painless-field-context]]
|
|
=== Field context
|
|
|
|
Use a Painless script to create a
|
|
{ref}/search-request-script-fields.html[script field] to return
|
|
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.
|
|
|
|
{ref}/mapping-source-field.html[`params['_source']`] (`Map`, read-only)::
|
|
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*
|
|
|
|
The standard <<painless-api-reference, Painless API>> is available.
|
|
|
|
|
|
*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] |