🏑 Home πŸ“– Chapter πŸ‘ˆ Prev πŸ‘‰ Next

⚑  ElasticsearchBook.com is crafted by Jozef Sorocin and powered by:

Script Fields in Practice

As mentioned in the chapter Aggregation Data Tables, each individual hit returned from a _search request can contain custom attributes generated on-the-fly through a script.

These custom attributes (script fields) are typically either:

A _search request can specify more than one script field at once:

POST myindex/_search
{
  "script_fields": {
    "using_doc_values": {
      "script": "doc['price'].value * 42"
    },
    "using_source": {
      "script": "params['_source']['price'] * 42"
    }
  }
}

Unlike in script queries where you can only access doc_values, script fields also allow for accessing the original document _source.

<aside> ⚠️ Quoting the docs: the doc[...] notation will cause the terms for that field to be loaded to memory (cached), which will result in faster execution. But keep in mind that this notation only allows for accessing simple-valued fields (you can’t get a JSON object from it β€” only from the _source). You can, however, target array fields too, as I've shown here.

</aside>

<aside> πŸ’‘ Despite the fact that accessing _source directly will be slower that accessing the doc-values, scripts in script fields are only executed for the top N documents. As such, they aren't really a big performance consideration β€” particularly when you imagine that your request’s [size](<https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html>) would typically be in the lower double digits.

I discuss script speed in more detail in the parent chapter.

</aside>


Script fields can be used in Kibana charts as a means of data cleansing but also as part of regular _search requests.

Use Case: Script Field Possibilities for Various Data Types

Given an index containing smartphones: