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.

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

8 Comments

"_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 ?
Yes, the template needs to be stored as a string in that case
there is no option without breaking the JSON format?
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?
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.