Elasticsearch Mustache 可选参数

Eva*_*kas 5 java templates mustache elasticsearch elasticsearch-template

我一直在努力使用 Elasticsearch 模板,特别是在可选参数方面。我想在那里添加可选的过滤器。这是我正在尝试的代码片段:

{
  "filter" : {
    "bool" : {
      "must" : [
        {{#ProductIDs.0}}
        { "terms" : { "Product.ProductID" : [{{#ProductIDs}}{{.}},{{/ProductIDs}}] } }
        {{/ProductIDs.0}}
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,我"用替换\",丑化它,将它包裹在 中{ "template" :"_snippet_above_" }

现在,当我尝试使用以下命令调用它时:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": [1,2]
    }
}
Run Code Online (Sandbox Code Playgroud)

它忽略我提供的参数,但是当我尝试在官方 Mustache.io 演示页面中执行此操作时 - 它工作得很好。

{{#ProductIDs.length}}也尝试过选项 - 但没有成功。经过一些研究后,我发现Mustache.jsMustache.java之间有一个区别。我假设Elasticsearch使用JAVA版本,它不支持长度参数,所以我必须依赖isEmpty。所以我重写了我的查询如下:

{
  "filter" : {
    "bool" : {
      "must" : [
        {{^ProductIDs.isEmpty}}
        { "terms" : { "Product.ProductID" : [{{#ProductIDs}}{{.}},{{/ProductIDs}}] } }
        {{/ProductIDs.isEmpty}}
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我使用 ProductIDs 列表查询模板时 - 它工作正常,但是如果我删除参数,它不会带来任何结果。我假设它会生成这个:

{
  "filter" : {
    "bool" : {
      "must" : [
        { "terms" : { "Product.ProductID" : [] } }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我发送空数组作为参数 - 它工作正常。

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": []
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为发生这种情况是因为"ProductIDs"areundefined并且不为空。

有没有办法在 Mustache.java 中消除这种情况,以便我可以忽略这些参数?

太长;博士; 问题是,如果我没有通过模板在搜索请求中指定参数,我的条件将呈现为空数组,请参阅以下内容:

{
  "filter" : {
    "bool" : {
      "must" : [
        { "terms" : { "Product.ProductID" : [] } }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我传递空数组作为参数,请参阅以下内容:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": []
    }
}
Run Code Online (Sandbox Code Playgroud)

它按预期工作,并且不会生成我的模板中描述的过滤条件,因为数组中没有任何数据。

我要这个:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
    }
}
Run Code Online (Sandbox Code Playgroud)

与此相同的工作方式:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": []
    }
}
Run Code Online (Sandbox Code Playgroud)

kee*_*ety 3

解决方法可能不是最优雅的方法是将模板查询更改为子句并为空列表should添加子句。match_all

例子:

{
    "filter" : { 
        "bool" : {
            "should" : [  
                { "terms" : { "status" : [ "{{#ProductIDs}}","{{.}}","{{/ProductIDs}}"] }} 
                {{^ProductIDs}},
                {"match_all":{}}
                {{/ProductIDs}}
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)