Elasticsearch数组属性必须包含给定的数组项 [英] Elasticsearch array property must contain given array items

查看:382
本文介绍了Elasticsearch数组属性必须包含给定的数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档看起来像:

{
    "tags" => [
        "tag1",
        "tag2",
    ],
    "name" => "Example 1"
}

{
    "tags" => [
        "tag1",
        "tag3",
        "tag4"
    ],
    "name" => "Example 2"
}

我现在想要的是进行术语搜索,其中给定的数组可能看起来像这样:

What I now want is to do a terms search where given array might look like:

[tag1, tag3]

预期点击率应为:

{
    "tags" => [
        "tag1",
        "tag3",
        "tag4"
    ],
    "name" => "Example 2"
}

但是,当我进行如下查询时:

However, when I do a query like:

GET _search
{
    "query": {
        "filtered": {
           "query": {
               "match_all": {}
           },
           "filter": {
               "bool": {
                   "must": [
                      {
                          "terms": {
                             "tags": [
                                "tag1",
                                "tag3"
                             ]
                          }
                      }
                   ]
               }
           }
       }
    }
}

由于示例1和示例2都包含tag1或tag3,因此获得了示例1"和示例2"作为匹配.通过查看文档中的术语,我发现这些术语实际上是一个包含查询.

I get both "Example 1" and "Example 2" as hits since both Example 1 and Example 2 contains either tag1 or tag3. By looking at the documentation for terms I figured out that terms is actually a contains query.

在这种情况下,如何确保示例2是使用tag1和tag3查询时唯一的匹配?

How can I in this case make sure that Example 2 is the only hit when querying with tag1 and tag3?

推荐答案

您需要设置 添加到terms过滤器中,将query-dsl-terms-filter.html"rel =" nofollow>执行模式 更改为"和"所有条款都必须包含在文档中才能被视为匹配项

You need to set the execution mode to "and" by adding "execution": "and" to the terms filter so that all terms must be contained within a document to be considered a match

GET _search
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "terms": {
               "tags": [
                  "tag1",
                  "tag3"
               ],
               "execution": "and"
            }
         }
      }
   }
}

这实际上与使用所有术语的结合来构建bool must过滤器相同,但是形式更紧凑.

This is effectively the same as building a bool must filter with the conjunction of all terms, but in a more compact form.

这篇关于Elasticsearch数组属性必须包含给定的数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆