I often need to compute some fields of a Elasticsearch record and make it part of the result.
For example, I have this document:
{ "fields": { "connected": [true], "incall": [false], "timestamp": ["2021-09-02T10:35:06.000Z"] } }
And I want to have a field named "lack_of_optimization" which is 1 when "connected" is "true" AND "incall" is "false"
See this from the point of view of a callcenter manager:
when the callcenter agent is "connected" but not in call,
it can be rated as a lack of optimization
In other words:
if( connected && incall) lack_of_optimization = 0 else lack_of_optimization = 1
To achieve this, we need to write a script that will compute the value of the fields "connected" and "incall" then return a 0 or a 1 depending on the result. HEre is the query:
{ "size": 750, "sort":[ { "timestamp":{ "order":"desc", "unmapped_type":"boolean" } } ], "fields": [ {"field": "incall"}, {"field": "connected"} ], "script_fields":{ "lack_of_optimization":{ "script":{ "source":""" if (doc['connected'].value == true && doc['incall'].value == true) { 0; } else { 1; } """ } } }, "_source":false, "query":{ "bool":{ "must":[], "filter":[ {"match_all":{}}, { "range":{ "timestamp":{ "gte":"2021-08-15T00:30:00+0300", "lte":"2021-08-15T01:00:00+0300", "format":"strict_date_optional_time" } } }, {"match_phrase":{"connected":true}} ], "should":[], "must_not":[] } } }
The needed script is the value of the "source"
"script_fields":{ "animation_value":{ "script":{ "source":""" if (doc['connected'].value == true && doc['incall'].value == true) { 0; } else { 1; } """ } }
In the Elasticsearch documentation, it is refered as a "script field", written in the "Painless language"
The final document will then include the computed field:
{ "fields" : { "connected" : [ true ], "incall" : [ false ], "lack_of_optimization" : [ 1 ] } }