0

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.

Amit Chauhan
  • 1,810
  • 3
  • 17
  • 25

1 Answers1

1

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"]
Val
  • 207,596
  • 13
  • 358
  • 360
  • "_source": {{#toJson}}fields{{/toJson}} this will be inside double quotes "" ? if not then it will not be a valid JSON so then I need to upload search template as string ? – Amit Chauhan Mar 11 '21 at 13:30
  • 1
    Yes, the template needs to be stored as a string in that case – Val Mar 11 '21 at 13:31
  • there is no option without breaking the JSON format? – Amit Chauhan Mar 11 '21 at 14:12
  • Search templates are written in the mustache syntax, so since `{{#toJson}}...{{/toJson}}` is not real JSON, you need to use text instead. Is this an issue? – Val Mar 11 '21 at 14:17
  • i want to add a condition there too like if some one does not pass field value in request then all values should be return for that I am trying to do => ```{{#fields}} \"source\" : {{#toJson}}fields{{/toJson}},{{/fields}}```` but it's not helping giving error of duplicate fields. – Amit Chauhan Mar 12 '21 at 13:25
  • The format is not in a readable format as it's a single-line string. How can I make it into a more readable format? – Amit Chauhan Mar 16 '21 at 12:01
  • Please create a new question referencing this one, as this one was answered and we should not handle too many topics per thread. – Val Mar 16 '21 at 12:10
  • Hi you can found new question link https://stackoverflow.com/questions/66656722/related-to-previous-question-how-can-we-format-string-escaped-value – Amit Chauhan Mar 16 '21 at 15:03