0

我们在使用 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_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"
  }
}
4

1 回答 1

0

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

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

然后,调用该查询的正确方法是这样的(即,您缺少fromparams 对象中的变量):

{
  "id": "dateTemplate",
  "params": {
    "query_string": "*",
    "since": {
      "from": "2018-07-23"
    }
  }
}
于 2019-01-07T04:39:09.340 回答