对应72.官放文档路径:Search APIs » Search Template
官方地址如下:
https://www.elastic.co/guide/en/elasticsearch/reference/7.2/search-template.html
Search template允许使用mustache语言预先设置查询请求,在执行查询请求之前使用参数进行填充请求。
1. 存储一个查询模板:
POST _scripts/<templateid>
{
"script": {
"lang": "mustache",
"source": {
"query": {
"match": {
"title": "{{query_string}}"
}
}
}
}
}
2. 查询一个查询模板:
GET _scripts/<templateid>
3. 删除一个查询模板:
DELETE _scripts/<templateid>
4. 使用一个查询模板进行查询:
GET _search/template
{
"id": "<templateid>",
"params": {
"query_string": "search for these words"
}
}
5. 填充参数呈现查询模板:
GET _render/template
{
"source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}",
"params": {
"statuses": {
"status": [
"pending",
"published"
]
}
}
}
GET _render/template/<template_name>
{
"params": {
"..."
}
}
使用模板时可以使用explain和profile API
6. 将参数转为json格式:
{{#toJson}}parameter{{/toJson}}含义为将参数parameter:后面的内容替换到当前位置
GET _search/template
{
"source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}",
"params": {
"statuses" : {
"status": [ "pending", "published" ]
}
}
}
结果为:
{
"query": {
"terms": {
"status": [
"pending",
"published"
]
}
}
}
7. 拼接为数组:
{{#join}}array{{/join}}可以将数组改为逗号连接的字符串
GET _search/template
{
"source": {
"query": {
"match": {
"emails": "{{#join}}emails{{/join}}"
}
}
},
"params": {
"emails": [ "username@email.com", "lastname@email.com" ]
}
}
结果为:
{
"query" : {
"match" : {
"emails" : "username@email.com,lastname@email.com"
}
}
}
{{#join delimiter='||'}}date.formats{{/join delimiter='||'}也可以自定义分隔符
8. 设定默认值:
{{var}}{{^var}}default{{/var}}:含义为var参数变量默认值为default
9. 设置条件语句(当参数为非必填时使用)
使用条件语句必须将作为字符串传递,不能使用json格式。例:在line字段上运行match查询,还可以选择按行号过滤,start和end为可选填的,参数如下:
{
"params": {
"text": "words to search for",
"line_no": {
"start": 10,
"end": 20
}
}
}
查询按如下方式构造:
{
"query": {
"bool": {
"must": {
"match": {
"line": "{{text}}"
}
},
"filter": {
{{#line_no}}
"range": {
"line_no": {
{{#start}}
"gte": "{{start}}"
{{#end}},{{/end}}
{{/start}}
{{#end}}
"lte": "{{end}}"
{{/end}}
}
}
{{/line_no}}
}
}
}
}
因为包含部分标记{{#start }},所以在使用时需要将其转为字符串,转换方式如下:
将上面json格式的query语句使用""包裹,并将内部"进行转义("前添加\)
编码url:
{{#url}}value{{/url}}对字符串进行html编码
GET _render/template
{
"source" : {
"query" : {
"term": {
"http_access_log": "{{#url}}{{host}}/{{page}}{{/url}}"
}
}
},
"params": {
"host": "https://www.elastic.co/",
"page": "learn"
}
}
结果如下:
{
"template_output": {
"query": {
"term": {
"http_access_log": "https%3A%2F%2Fwww.elastic.co%2F%2Flearn"
}
}
}
}
网友评论