gpt4 book ai didi

elasticsearch - 如何处理 elasticsearch 模板中的过滤器?

转载 作者:行者123 更新时间:2023-12-02 22:21:15 24 4
gpt4 key购买 nike

我有类似的数据集可用于 Elasticsearch。

  {
"id" :1,
"title" : "Toy Story 1",
"year" : 1995 ,
"category" : "Adventure"
},
{
"id" :2,
"title" : "Jumanji",
"year" : 1995,
"category" : "Adventure"
},
{
"id" :3,
"title" : "Grumpier Old Men",
"year" : 1996,
"category" : "Comedy"
},
{
"id" :4,
"title" : "Toy Story 2",
"year" : 1996,
"category" : "Action"
},
{
"id" :5,
"title" : "Toy Story 3"
"year" : 1997
"category" : "Comedy"
},
{
"id" :6,
"title" : "Toy Story 4"
"year" : 2019
"category" : "Comedy"
}

这是我的索引的映射。
{
"movies": {
"mappings": {
"properties": {
"category": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"id": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"year": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}

我正在使用搜索模板来检索数据。
我创建了一个模板并通过传递模板的 id 来查询数据。

您可以引用以下链接。
Search-template

我正在使用 postman 创建模板并使用模板查询数据。

我创建的模板如下:

POST _scripts/测试
{
"script": {
"lang": "mustache",
"source": {
"query": {
"match": {
"title": "{{query_string}}"
}
}
}
}
}

POST _search/模板
{
"id": "test",
"params": {
"query_string": "toy"
}
}

这工作正常。我得到了预期的结果。

现在我坚持使用模板中的过滤选项。

我想过滤类别。我想在模板中添加类别并将值传递为 ["Comedy", "Adventure"]
我们如何在模板中添加过滤器并将数组值传递给它?

最佳答案

你可以这样做。首先像这样修改你的脚本模板:

POST _scripts/test
{
"script": {
"lang": "mustache",
"source": """
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "{{query_string}}"
}
}
],
"filter": [
{
"terms": {
"category.keyword": {{#toJson}}categories{{/toJson}}
}
}
]
}
}
}
"""
}
}

请注意,上述内容只能在 Kibana Dev Tools 中执行(因为有三重引号 ( """ ))。

如果您在其他地方执行此操作,则需要先对查询进行 JSON 编码:
POST _scripts/test
{
"script": {
"lang": "mustache",
"source": "{\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"match\": {\n \"title\": \"{{query_string}}\"\n }\n }\n ],\n \"filter\": [\n {\n \"terms\": {\n \"category.keyword\": {{#toJson}}categories{{\/toJson}}\n }\n }\n ]\n }\n }\n }"
}
}

然后你可以这样称呼它:
POST _search/template
{
"id": "test",
"params": {
"query_string": "toy",
"categories": [
"Comedy",
"Adventure"
]
}
}

它将产生这个查询:
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "toy"
}
}
],
"filter": [
{
"terms": {
"category": [
"Comedy",
"Adventure"
]
}
}
]
}
}
}

关于elasticsearch - 如何处理 elasticsearch 模板中的过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com