6.elasticsearch中search template和alias

发布时间 2024-01-05 10:41:10作者: 赛博朋克V

什么是search template

顾名思义,查询模版,就是提前设定好查询的DSL,再次查询时,只需要指定对应的模版,然后传入相应的参数就好。一是可以每次不用构建复杂的DSL,二是可以供开发直接使用查询DSL模版,减少学习和对接成本。

有如下两种方法

一、创建脚本_script/template,然后使用此模版

#创建脚本
POST _scripts/mytemplate
{
  "script":{
    "lang": "mustache",
    "source": {
        "query": {
            "term": {
                "{{key}}":"{{query_string}}"
            }
        }
    }
  }
}

#对某个索引使用脚本
GET movies/_search/template
{
  "id":"mytemplate",
  "params": {
      "key":"title",
    "query_string":"love"
  }
}

二、在es安装目录config/scripts文件夹下,添加.mustache文件

{
    "query":{
      "match": {
             "{{match_field}}":"{{match_value}}"
        }
      },
      "post_filter":{
        {{#isCondition}}
            "range":{
                "{{range_field}}":{
                   {{#start}}
                      "gte":{{start}}
                       {{#end}},{{/end}}
                    {{/start}}

                   {{#end}}
                       "lte":{{end}}
                   {{/end}}
                  }
                }

        {{/isCondition}}

      }
  }
}

查询语句:

GET book/book/_search/template
{
  "file":"match_condition",
  "params": {
    "match_field":"bookAuthor",
    "match_value":"陈寅恪",
    "isCondition":true,
    "range_field":"bookPrice",
    "start":10,
    "end": 10
  }
}