学习es的查询模板必须得先知道Mustache(胡子)语法
{{data}} {{#data}} {{/data}} {{^data}} {{/data}} {{.}} {{<partials}} {{{data}}} {{!comments}}
写查询模板
PUT _search/template/people_search_single_test { "template": { "query":{ "match":{ "name":"{{name}}" } } } }
查数据用查询模板(前提的有数据)
,注意关键词id
GET family_index/people/_search/template { "id":"people_search_single_test", "params":{ "name":"li yan" } }
在es路径下config/scripts中,创建文件,后缀名必须为
.mustache
,例如:people_search_single_test.mustache
内容如下
写文件people_search_single_test.mustache
{ "query": { "bool": { "must": { "match": { "name": "{{name}}" } } } } }
查数据
GET family_index/people/_search/template { "file":"people_search_single_test", "params":{ "name":"li yan" } }
之前看官网介绍对查询模板很疑惑,会使用一种
内联
查询的方式,觉得很鸡肋,如下:毫无意义(模板就是为了简便,这样写就没有意义了)GET family_index/people/_search/template { "template": { "query":{ "match":{ "name":"{{name}}" } } }, "params":{ "name":"li yan" } }
如果担心写的查询模板会有错误,那可以使用
_render
,带个参数进去验证#写 PUT _search/template/people_search_single_test { "template": { "query":{ "match":{ "name":"{{name}}" } } } } #查 GET _render/template/people_search_single_test { "params": { "name": "li yan" } } #-------结果---------- { "template_output": { "query": { "match": { "name": "li yan" } } } }
{{parameter}}
:传参
{{#parameter}}{{/parameter}}
:若模板名称对应的参数不存在或者返回为false,那么此对标签包裹的内容将不显示
{{^parameter}}{{/parameter}}
:和上面一个相反,若模板名称对应的参数不存在或者返回为false,那么此对标签包裹的内容将显示
{{!我爱上班}}
:注释
{{#toJson}}{{/toJson}}
:转为JSON,一般针对对象的内容
{{#join}}{{/join}}
:拼接,默认,
{{#join delimiter='||'}}{{/join delimiter='||'}}
:自定义拼接符号
{{#url}}{{/url}}
:对URL转码
文件名为:
people_search_complex_test.mustache
,用好{{#parameter}}{{/parameter}}
和{{^parameter}}{{/parameter}}
相当于if else
{ "query": { "bool": { "must": { "match": { "name": "{{name}}" } }, "filter": { {{#information}} "range": { "information.height": { {{#start}} "gte": "{{start}}" {{#end}},{{/end}} {{/start}} {{#end}} "lte": "{{end}}" {{/end}} } } {{/information}} {{^information}} "gte":"160", "lte":"190" {{/information}} } } }, "from": "{{from}}", "size": "{{size}}", "aggs": { "people_height_avg": { "avg": { "field": "information.height" } } }, "sort": { "information.height": { "order": "desc" } } }
#--查-- GET family_index/people/_search/template { "file": "people_search_complex_test", "params": { "name": "xiao li", "from": "0", "size": "2", "information":{ "start":150, "end":170 } } }
#--验算结果-- { "template_output": { "query": { "bool": { "must": { "match": { "name": "li yan" } }, "filter": { "range": { "information.height": { "gte": "150", "lte": "170" } } } } }, "from": "0", "size": "2", "aggs": { "people_height_avg": { "avg": { "field": "information.height" } } }, "sort": { "information.height": { "order": "desc" } } } }