文章目录

  • 1. Search Template简介
  • 2. 样例Examples
    • 1. 存储一个template Store a search template

1. Search Template简介

/_search/template api 允许使用mustache(小胡子)语言在执行搜索请求之前预渲染它们,并使用模板参数填充现有模板。

The /_search/template endpoint allows to use the mustache language to pre render search requests, before they are executed and fill existing templates with template parameters.

GET _search/template
{"source" : {"query": { "match" : { "{{my_field}}" : "{{my_value}}" } },"size" : "{{my_size}}"},"params" : {"my_field" : "message","my_value" : "some message","my_size" : 5}
}

For more information on how Mustache templating and what kind of templating you can do with it check out the online documentation of the mustache project.

The mustache language is implemented in Elasticsearch as a sandboxed scripting language, hence it obeys settings that may be used to enable or disable scripts per type and context as described in the scripting docs

2. 样例Examples

1. 存储一个template Store a search template

You can store a search template using the stored scripts API.

POST _scripts/<templateid>
{"script": {"lang": "mustache","source": {"query": {"match": {"title": "{{query_string}}"}}}}
}

This template can be retrieved by

获取template

GET _scripts/<templateid>返回{"script" : {"lang" : "mustache","source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}","options": {"content_type" : "application/json; charset=UTF-8"}},"_id": "<templateid>","found": true
}

This template can be deleted by

删除template

DELETE _scripts/<templateid>

使用存储的template来进行搜索

GET _search/template
{"id": "<templateid>", "params": {"query_string": "search for these words"}
}

id是stored template的script name

校验一个search template
Validate a search template

A template can be rendered in a response with given parameters using

GET _render/template
{"source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}","params": {"statuses" : {"status": [ "pending", "published" ]}}
}

This call will return the rendered template:
返回渲染后的template

{"template_output": {"query": {"terms": {"status": [ "pending","published"]}}}
}

status array has been populated with values from the params object.

Stored templates can also be rendered using

也可以使用store的template进行渲染

GET _render/template/<template_name>
{"params": {"..."}
}

Explain
使用explain参数来看渲染的详情

GET _search/template
{"id": "my_template","params": {"status": [ "pending", "published" ]},"explain": true
}

Profiling
You can use profile parameter when running a template:
使用profile参数来进行性能分析

GET _search/template
{"id": "my_template","params": {"status": [ "pending", "published" ]},"profile": true
}

Filling in a query string with a single value

使用单个value来填充query string

GET _search/template
{"source": {"query": {"term": {"message": "{{query_string}}"}}},"params": {"query_string": "search for these words"}
}

将参数转成json
Converting parameters to JSON
The {{#toJson}}parameter{{/toJson}} function can be used to convert parameters like maps and array to their JSON representation:

GET _search/template
{"source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}","params": {"statuses" : {"status": [ "pending", "published" ]}}
}

which is rendered as:

{"query": {"terms": {"status": ["pending","published"]}}
}

A more complex example substitutes an array of JSON objects:

GET _search/template
{"source": "{\"query\":{\"bool\":{\"must\": {{#toJson}}clauses{{/toJson}} }}}","params": {"clauses": [{ "term": { "user" : "foo" } },{ "term": { "user" : "bar" } }]}
}

which is rendered as:

{"query" : {"bool" : {"must" : [{"term" : {"user" : "foo"}},{"term" : {"user" : "bar"}}]}}
}

连接数组中的元素
Concatenating array of values
The {{#join}}array{{/join}} function can be used to concatenate the values of an array as a comma delimited string:

GET _search/template
{"source": {"query": {"match": {"emails": "{{#join}}emails{{/join}}"}}},"params": {"emails": [ "username@email.com", "lastname@email.com" ]}
}

which is rendered as:

{"query" : {"match" : {"emails" : "username@email.com,lastname@email.com"}}
}

默认使用逗号进行连接",", 也可以自定义连接符
The function also accepts a custom delimiter:

GET _search/template
{"source": {"query": {"range": {"born": {"gte"   : "{{date.min}}","lte"   : "{{date.max}}","format": "{{#join delimiter='||'}}date.formats{{/join delimiter='||'}}"}}}},"params": {"date": {"min": "2016","max": "31/12/2017","formats": ["dd/MM/yyyy", "yyyy"]}}
}

which is rendered as:


{"query" : {"range" : {"born" : {"gte" : "2016","lte" : "31/12/2017","format" : "dd/MM/yyyy||yyyy"}}}
}

默认值

Default values
default value is written as {{var}}{{^var}}default{{/var}} for instance:

{"source": {"query": {"range": {"line_no": {"gte": "{{start}}","lte": "{{end}}{{^end}}20{{/end}}"}}}},"params": { ... }
}

When params is { “start”: 10, “end”: 15 } this query would be rendered as:

{"range": {"line_no": {"gte": "10","lte": "15"}}
}

But when params is { “start”: 10 } this query would use the default value for end:

{"range": {"line_no": {"gte": "10","lte": "20"}}
}

条件语句
Conditional clauses
条件子句不能使用模板的JSON形式表示。而是必须将模板作为字符串传递。例如,假设我们要在行字段上运行匹配查询,并希望按行号进行过滤,其中开始和结束是可选的。

Conditional clauses cannot be expressed using the JSON form of the template. Instead, the template must be passed as a string. For instance, let’s say we wanted to run a match query on the line field, and optionally wanted to filter by line numbers, where start and end are optional.

The params would look like:

{"params": {"text":      "words to search for","line_no": { "start": 10,"end":   20}}
}

The line_no, start, and end parameters are optional.

We could write the query as:

{"query": {"bool": {"must": {"match": {"line": "{{text}}"  1}},"filter": {{{#line_no}} 2"range": {"line_no": {{{#start}}  3"gte": "{{start}}" 4{{#end}},{{/end}}  5{{/start}}{{#end}} 6"lte": "{{end}}" 7{{/end}}}}{{/line_no}}}}}
}
  1. 填充param text, Fill in the value of param text
  2. 检测到line_no参数则包含range filter, Include the range filter only if line_no is specified
  3. 检测到line_no.start 则包含gte 条件, Include the gte clause only if line_no.start is specified
  4. 填充line_no.start 的value, Fill in the value of param line_no.start
  5. 在检测到line_no.start AND line_no.end的时候填充一个逗号",", Add a comma after the gte clause only if line_no.start AND line_no.end are specified
  6. 检测到line_no.end 的时候包含lte条件,Include the lte clause only if line_no.end is specified
  7. 填充line_no.end的value, Fill in the value of param line_no.end

As written above, this template is not valid JSON because it includes the section markers like {{#line_no}}. For this reason, the template should either be stored in a file (see Store a search template) or, when used via the REST API, should be written as a string:

"source": "{\"query\":{\"bool\":{\"must\":{\"match\":{\"line\":\"{{text}}\"}},\"filter\":{{{#line_no}}\"range\":{\"line_no\":{{{#start}}\"gte\":\"{{start}}\"{{#end}},{{/end}}{{/start}}{{#end}}\"lte\":\"{{end}}\"{{/end}}}}{{/line_no}}}}}}"

使用url编码
Encoding URLs
{{#url}}value{{/url}} 功能可以用来将参数进行url编码
The {{#url}}value{{/url}} function can be used to encode a string value in a HTML encoding form as defined in by the HTML specification.

As an example, it is useful to encode a URL:

GET _render/template
{"source" : {"query" : {"term": {"http_access_log": "{{#url}}{{host}}/{{page}}{{/url}}"}}},"params": {"host": "https://www.elastic.co/","page": "learn"}
}The previous query will be rendered as:{"template_output" : {"query" : {"term" : {"http_access_log" : "https%3A%2F%2Fwww.elastic.co%2F%2Flearn"}}}
}

04.search_template相关推荐

  1. docker 配置使用宿主机的GPU(ubuntu16.04+cuda10.0+cudnn7)

    1. 安装 Docker 卸载旧版本 Docker sudo apt-get remove docker docker-engine docker.io containerd runc 安装新版本 s ...

  2. Ubuntu 16.04 安装后修改屏幕分辨率(xrandr: Failed to get size of gamma for output default)

    ubuntu 16.04 安装后分辨率只有一个选项 1024x768,使用 xrandr 命令出现错误: xrandr: Failed to get size of gamma for output ...

  3. Ubuntu 16.04 安装 Docker - Dependency failed for Docker Application Container

    Docker 安装 由于 apt 官方库里的 Docker 版本可能比较旧,所以先卸载可能存在的旧版本: sudo apt-get remove docker docker-engine docker ...

  4. 【Docker】Ubuntu18.04国内源安装Docker-准备工作(一)

    前言: 安装docker由于很多教程都使用国外源和阿里源,安装失败,这里总结一种国内源的安装方法,亲测有效! 过程: 步骤1:在服务器上创建虚拟机 远程连接服务器,win+R--输入mstsc---- ...

  5. 在Ubuntu18.04上安装opencv 3.4.1

    对于安装opencv有的人一次就成功,而有人安装了N多次才成功.我就是那个安装了N多次的人,每次遇到了很多安装错误,只能通过到网上搜教程资料,解决方法:通过一次次的试错,最终完成了安装.再此提醒第一次 ...

  6. Go 中 time.Parse 报错:year/month/day hour/minute/second out of range 时间格式化为什么是 2006-01-02 15:04:05?

    1. 问题现象 在使用 Go 语言的 time.Parse 解析时间时遇到以下错误: func main() {timeParse, err := time.Parse("2006-11-0 ...

  7. Go 学习笔记(25)— 并发(04)[有缓冲/无缓冲通道、WaitGroup 协程同步、select 多路监听通道、close 关闭通道、channel 传参或作为结构体成员]

    1. 无缓冲的通道 无缓冲的通道(unbuffered channel)是指在接收前没有能力保存任何值的通道. 这种类型的通道要求发送 goroutine 和接收 goroutine 同时准备好,才能 ...

  8. ubuntu14.04安装hadoop2.6.0(伪分布模式)

    版本:虚拟机下安装的ubuntu14.04(64位),hadoop-2.6.0 下面是hadoop2.6.0的官方英文教程: http://hadoop.apache.org/docs/r2.6.0/ ...

  9. Ubuntu 12.04安装Sun JDK 6

    Ubuntu 12.04安装Sun JDK 6 下载 sun jdk 6 bin. 设置权限 chmod +x jdk-6u25-linux-i586.bin 解压文件 ./jdk-6u25-linu ...

最新文章

  1. Deepmind AlphaStar 如何战胜人类职业玩家【中科院自动化所深度解析】
  2. php中使用like查询,php like 查询
  3. 世界奥运建筑文学第一书  北京奥运长篇纪实第一人
  4. .NET 6 Preview 1 开箱,带你体验新版本
  5. 第三方测评:GaussDB(for Redis)稳定性与扩容表现
  6. numpy 基础 —— np.linalg
  7. E8.Net工作流开发架构
  8. 百词斩不复习_不背单词好用还是百词斩好用?
  9. 猪齿鱼_01_环境搭建(一)_微服务支撑组件部署(源码形式)
  10. 小米蓝牙广播数据解析(MiBeacon)
  11. mysql rank_MySQL实现rank排名(一)自定义变量@rank
  12. java bigdecimal 取整数_java-检查BigDecimal是否为整数值
  13. UltraEdit+Masm--打造自己的汇编IDE
  14. 2021 An Updated Comparison of Four Low Earth Orbit Satellite Constellation Systems to Provide Global
  15. 华为手机wifi不显示连接到服务器,华为手机无线网已经连接但不能用怎么办
  16. VUE Object.assign()的使用
  17. 全局壁纸,让你喜欢的壁纸无处不在
  18. CAN总线学习笔记(2)- CAN协议数据帧与遥控帧
  19. WiFi开发|WiFi无线技术介绍
  20. matlab求解拉普拉斯方程,急求用matlab编写解拉普拉斯方程的程序

热门文章

  1. lcx源代码以及免杀的研究
  2. 秒杀多线程第十一篇 读者写者问题
  3. BPF、eBPF、XDP 和 Bpfilter……这些东西是什么?
  4. 集群管理工具KafkaAdminClient——改造
  5. 用Starlink填补5G和光纤之间的空白
  6. Netflix在安卓移动启用AV1格式 较VP9编码效率提升20%
  7. LiveVideoStack线上交流分享 ( 五 ) —— 在线教育音视频技术探索与应用
  8. LeetCode——二分查找
  9. 即将直播:新一代大数据技术构建PB级云端数仓实践
  10. PMP之项目整合管理之变更管理计划