如何在Elasticsearch搜索模板中使_source字段动态化? [英] How to make _source field dynamic in elasticsearch search template?

查看:61
本文介绍了如何在Elasticsearch搜索模板中使_source字段动态化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在弹性搜索中使用搜索查询时,我们定义了响应中需要哪些字段

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

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

在使用搜索模板时,我们必须在将搜索模板插入ES群集时设置_source字段值.

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"
  }
}

此搜索查询返回 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.

推荐答案

绝对!

您的搜索模板应如下所示:

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"]

这篇关于如何在Elasticsearch搜索模板中使_source字段动态化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆