采用mustache语言作为elasticsearch搜索请求的预处理模板

      在朱林编著的《elasticsearch技术解析与实战》一书中第164页至166页----搜索模版这一部分,书中例举了三种使用模板的方式,在这里要着重提一下最后一种,书中原文:可以使用Mustache语言作为搜索请求的预处理,它提供了模板,然后通过键值对来替换模板中的变量。把脚本存储在本地磁盘中,默认的位置为:elasticsearch\config\scripts,通过引用脚本名称进行使用。

     紧接着说:在操作前,先要把脚本存储在文件中,文件名为template_test.mustache,文件中的内容为:

{

    "template": {         "query": {             "match": {                 "eventName": "{{query_string}}"             }         }     } }

 我把template_test.mustache放到了elasticsearch\config\scripts文件夹下面后,书中又说elasticsearch对文件读取有个时间,刚建好后,不能生效,做验证的时候可以重启进行生效。于是我重启了后跟着书上的例子做验证:

请求:POST http://127.0.0.1:9200/secisland/_search/
{
    "query": {
        "template": {
            "id": "template_test",
            "params": {
                "query_string": "linux"
            }
        }
    }
}
结果报错了:

{ 
 
 
  • "error": {
    • "root_cause": [
      • {
        • "type": "illegal_argument_exception",
        • "reason": "Unable to find script [.scripts/mustache/template_test]"
        }
      ],
    • "type": "search_phase_execution_exception",
    • "reason": "all shards failed",
    • "phase": "query",
    • "grouped": true,
    • "failed_shards": [
      • {
        • "shard": 0,
        • "index": "secisland7",
        • "node": "0omSZJbpQcKFTc7Ju_g0RQ",
        • "reason": {
          • "type": "illegal_argument_exception",
          • "reason": "Unable to find script [.scripts/mustache/template_test]"
          }
        }
      ]
    },
  • "status": 400
}
        注意这句话:Unable to find script [.scripts/mustache/template_test],这证明采用mustache语言的搜索模板要放在elasticsearch\config\scripts\mustache\路径下面,我赶紧在scripts下面新建了mustache文件夹,将template_test.mustache放到该文件下面,再次重启服务并运行验证,还是不行,后来读到书的后半部分才发现书中写错了,当你采用真实的文件模板时,dsl查询语言参数中必须用file参数来指定文件模板名称,而不能再使用id参数,id参数只能用在已经将脚本存储在了elasticsearch中的情况(即模板已经有了索引的情况下);而我们这里是真实的文件模板,没有存储在elasticsearch中,所以要用file参数,改成如下就OK了

请求:POST http://127.0.0.1:9200/secisland/_search/
{
    "query": {
        "template": {
            "file": "template_test",
            "params": {
                "query_string": "linux"
            }
        }
    }
}
    这本书几乎全部是在浏览器的head插件(类似于postman)中进行操作的,只有两三页介绍Java API;而且翻译的痕迹非常明显,实战性不强,书中错误挺多的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值