elasticsearch 如何使用Moustache模板从字符串列表中获取术语子句的动态列表

wxclj1h5  于 2023-04-29  发布在  ElasticSearch
关注(0)|答案(2)|浏览(188)

我有一个字符串e的列表。g. items = ["red", "green", "blue", ...],我想使用模板来获取

"should": [
  {
    "term": {
      "mycolor": "red"
    }
  },
  {
    "term": {
      "mycolor": "green"
    }
  },
  {
    "term": {
      "mycolor": "blue"
    }
  },
  ...
]

现在我在努力

"should": [
  {{#items}}
  {
    "term": {
      "mycolor" : "{{.}}"
    }
  },
  {{/items}}
]

但它不起作用,因为结尾会有一个逗号。我怎样才能去掉后面的逗号来使它工作?

5q4ezhmt

5q4ezhmt1#

我自己找到了答案。Moustache是一个“无逻辑”的模板工具,所以似乎没有比我在这里尝试的更好的选择了。如果您有更好的想法,请添加答案或评论。
要呈现多个term子句并处理结尾的逗号,我可以

"should": [
  {{#items}}
  {
    "term": {
      "mycolor" : "{{color}}"
    }
  }
  {{^last}},{{/last}}
  {{/items}}
]

其中items是这样的对象列表

params: {
"items": [{
  "color": "red"
},
{
  "color": "green"
},
{
  "color": "blue",
  "last": 1
}]
}

使用^操作符,即“倒置部分”,模板知道当“last”出现时不呈现逗号。

更高级的案例

如果你必须在一些现有的条款上添加这个条款列表,e。例如,在“myssize”之上添加这些“mycolor”术语

"should": [
  {
    "term": {
      "mycolor": "red"
    }
  },
  {
    "term": {
      "mycolor": "green"
    }
  },
  {
    "term": {
      "mycolor": "blue"
    }
  },
  {
    "term": {
      "mysize": "xl"
    }
  },
  {
    "term": {
      "mysize": "l"
    }
  },
  ...
]

您将需要处理两个列表都为空的情况,并处理是否在它们之间添加逗号i。例如,如果“mysize”列表不为空,则“mycolor”应该有一个尾随逗号,否则不是。在这种情况下,我们需要根据第二个列表是否为空来呈现一个逗号。如果我们使用第二个列表sizes作为标签,它不起作用,因为Moustache将呈现逗号N次,其中N是sizes的长度。AFAIK没有办法基于非空列表渲染 once。因此,我必须引入另一个参数sizesExist,并在代码中设置它。

"should": [
  {{#colors}}
  {
    "term": {
      "mycolor" : "{{color}}"
    }
  }
  {{^last}},{{/last}}
  {{#sizesExist}},{{/sizesExist}}
  {{/colors}}
  {{#sizes}}
  {
    "term": {
      "mysize" : "{{size}}"
    }
  }
  {{^last}},{{/last}}
  {{/sizes}}
]

params: {
  "colors": [...],
  "sizes": [...],
  "sizesExist": true
}
kgsdhlau

kgsdhlau2#

在这个特定的例子中,可以使用terms query和mustache toJson运算符来展开colors数组

"should": [
  {{#colors.size}}
  {
    "terms": {
      "mycolor" : {{#toJson}}colors{{/toJson}}
    }
  }
  {{/colors.size}}
]
params: {colors: ["red", "green", "blue"]}

相关问题