java - Elasticsearch Mustache 可选参数

标签 java templates elasticsearch mustache elasticsearch-template

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

{
  "filter" : {
    "bool" : {
      "must" : [
        {{#ProductIDs.0}}
        { "terms" : { "Product.ProductID" : [{{#ProductIDs}}{{.}},{{/ProductIDs}}] } }
        {{/ProductIDs.0}}
      ]
    }
  }
}

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

现在,当我尝试使用以下方式调用它时:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": [1,2]
    }
}

它忽略了我提供的参数,但是当我尝试在官方 mustache.io 演示页面中这样做时 - 它工作得很好。

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

{
  "filter" : {
    "bool" : {
      "must" : [
        {{^ProductIDs.isEmpty}}
        { "terms" : { "Product.ProductID" : [{{#ProductIDs}}{{.}},{{/ProductIDs}}] } }
        {{/ProductIDs.isEmpty}}
      ]
    }
  }
}

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

{
  "filter" : {
    "bool" : {
      "must" : [
        { "terms" : { "Product.ProductID" : [] } }
      ]
    }
  }
}

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

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": []
    }
}

我认为这是因为 "ProductIDs"undefined 而不是空的。

有没有办法在 mustache.java 中包含此条件,以便我可以忽略这些参数?

tl;dr; 问题是,如果我没有通过模板在我的搜索请求中指定参数,我的条件将呈现为一个空数组,请参见:

{
  "filter" : {
    "bool" : {
      "must" : [
        { "terms" : { "Product.ProductID" : [] } }
      ]
    }
  }
}

如果我将空数组作为参数传递,请参见:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": []
    }
}

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

我想要这个:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
    }
}

像这样工作:

GET /statistic/_search/template
{
    "template": {
        "id": "test" 
    },
    "params": {
        "ProductIDs": []
    }
}

最佳答案

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

例子:

{
    "filter" : { 
        "bool" : {
            "should" : [  
                { "terms" : { "status" : [ "{{#ProductIDs}}","{{.}}","{{/ProductIDs}}"] }} 
                {{^ProductIDs}},
                {"match_all":{}}
                {{/ProductIDs}}
            ]
        }
    }
}

关于java - Elasticsearch Mustache 可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32219379/

相关文章:

c++ - generic int -> enum conversion with templates 可能吗?

C++:尝试在模板化类中声明和定义模板化类。我的代码有什么问题?

elasticsearch - 如何在ELK中启用date_nanos功能?

json - 通过talend上的REST请求发送json数据

java - Eclipse 调试器 : Threads vs "Daemon" Threads

java - 无法从 jetty 发布请求检索表单数据

c++ - 编译器如何从该 lambda 表达式推导出返回类型?

java - 无法连接到docker中的elasticsearch容器

java - 使用多个 onclicklistener 添加到 SharedPreference 值

java - Activity 仅在重新加载应用程序后加载首次按下的索引的数据