如何在 Elasticsearch 预注册的 mushache 模板中使用 tojson

How use tojson in pre-registered mushache template in Elasticsearch

如何在 Elasticsearch 预注册的 mushache 模板中使用术语

嗨,

我使用的是 Elasticsearch v5.6.3。在 kibana 控制台中,我尝试使用术语查询保存搜索模板。

POST _scripts/test-json
{
  "script": {
    "lang": "mustache",
    "source": {"query": {"filter": {"bool": {"must": [{"terms": {"beat.hostname": {{#tojson}}hostname{{/tojson}} } }] } } } }
  }
}

但是没有双引号我遇到语法错误。

我在 github 中看到了这个问题。 https://github.com/elastic/elasticsearch/issues/21648

我跟本期的样例一样改了模版,没有语法错误。但是我无法得到结果。

POST _scripts/test-json
{
  "script": {
    "lang": "mustache",
    "source": {"query": {"filter": {"bool": {"must": [{"terms": {"beat.hostname": ["{{hostname}}"] } }] } } } }
  }
}

然后我更改了模板:

POST _scripts/test-json
{
  "script": {
    "lang": "mustache",
    "source": {"query": {"filter": {"bool": {"must": [{"terms": {"beat.hostname": ["{{#tojson}}hostname{{/tojson}}}}"] } }] } } } }
  }
}

调用后,出现运行时错误。

  {
    "type": "json_parse_exception",
    "reason": "Unexpected character ('h' (code 104)): was expecting comma to separate Array entries\n at [Source: org.elasticsearch.common.bytes.BytesReference$MarkSupportingStreamInputWrapper@396f6738; line: 1, column: 190]"
  }

如何为预注册搜索模板中的术语发送一些参数?

谢谢。

此问题已解决。关键是 script.source 可以是包含查询 JSON.

的字符串
POST _scripts/test-json
{
  "script": {
    "lang": "mustache",
    "source": "{\"size\": 0, \"query\": {\"bool\": {\"must\": [{\"terms\": {\"beat.hostname\": {{#tojson}}hostname{{/tojson}} } } ] }}}"
  }
}

此脚本可以保存成功。然后像下面这样调用它:

GET _search/template
{
  "id": "test-json",
  "params": {
    "hostname": ["host-1", "host-2"]
  }
}

很难找到解决方案:-)