在elasticsearch中使用搜索模板查询日期范围

00jrzges  于 2021-06-15  发布在  ElasticSearch
关注(0)|答案(1)|浏览(609)

在elasticsearch中,我们使用搜索模板构建日期范围查询时遇到了一个问题。它工作得很好,只有一个条件子句,但是当提供多个条件时,我们会得到以下错误。

{
  "script": {
    "lang": "mustache",
    "source": "{
         \"query\":{
              \"bool\":{
                  \"must\":[
                     {{#since}}
                      {\"range\": 
                        {\"@timestamp\": 
                            {
                              {{#from}}\"from\":\"{{from}}\"{{/from}}
                            }
                         }
                       },{{/since}}
                       {\"query_string\":
                           {
                             \"query\":\"(title:({{query_string}}))\"
                           }
                        }
                      ]
                   }
                  }
               }"
             }
           }

错误:

{
error: {
root_cause: [
{
type: "general_script_exception",
reason: "Failed to compile stored script [dateTemplate] using lang [mustache]",
}
],
type: "general_script_exception",
reason: "Failed to compile stored script [dateTemplate] using lang [mustache]",
caused_by: {
type: "mustache_exception",
reason: "Improperly closed variable in query-template:1",
},
},
status: 500,
}

查询:
{“id”:“datetemplate”,“params”:{“query\u string”:“*”}
同样的方法也适用于此模板:

{
  "script": {
    "lang": "mustache",
    "source": "{\"query\":{\"bool\":{\"must\":[{{#since}}{\"range\": {\"@timestamp\": {\"from\": \"{{since}}\"}}},{{/since}}{\"query_string\":{\"query\":\"(title:({{query_string}}))\"}}]}}}"
  }
}

查询

{
  "id": "date",
  "params": {
    "query_string": "*",
    "since": "2018-07-23"
  }
}
jslywgbw

jslywgbw1#

首先,我建议您使用三重引号重写模板,因为它更易于阅读和维护,如下所示:

POST _scripts/dateTemplate
{
  "script": {
    "lang": "mustache",
    "source": """
      {
        "query": {
          "bool": {
            "must": [
              {{#since}}
              {
                "range": {
                  "@timestamp": {
                    {{#from}}"from": "{{from}}"{{/from}}
                  }
                }
              },
              {{/since}}
              {
                "query_string": {
                  "query": "(title:({{query_string}}))"
                }
              }
            ]
          }
        }
      }
    """
  }
}

然后,调用该查询的正确方法如下(即,您缺少 from params对象中的变量):

{
  "id": "dateTemplate",
  "params": {
    "query_string": "*",
    "since": {
      "from": "2018-07-23"
    }
  }
}

相关问题