elasticsearchkibanadslelasticsearch-queryelasticsearch-template

How to make _source field dynamic in elasticsearch search template?


While using search query in elastic search we define what fields we required in the response

"_source": ["name", "age"]

And while working with search templates we have to set _source fields value while inserting search template to ES Cluster.

"_source": ["name", "age"]

but the problem with the search template is that it will always return us name and age and to get other fields we have to change our search template accordingly.

Is there any way we can pass search fields from the client so that it will only return fields in response to which the user asked? I have achieved that just for one field like if you do this

"_source": "{{field}}"

then while search index via template you can do this

POST index_name/_search/template
{
  "id": template_id,
  "params": {
    "field": "name"
  }
}

This search query returning the name field in response but I could not find a way to pass it as in array or in another format so I can get multiple fields.


Solution

  • Absolutely!!

    Your search template should look like this:

    "_source": {{#toJson}}fields{{/toJson}}
    

    And then you can call it like this:

    POST index_name/_search/template
    {
      "id": template_id,
      "params": {
        "fields": ["name"]
      }
    }
    

    What it's going to do is to transform the params.fields array into JSON and so the generated query will look like this:

    "_source": ["name"]