首页 > 解决方案 > Elasticsearch 排除多个术语的关联

问题描述

我需要从我的搜索中排除不同术语的关联。有什么聪明的方法来做这种多项排除吗?

示例:假设我想获取所有用户,除了那些(姓氏是Doe(名字是JohnAnnie没有任何名字值)的用户。

预期结果示例:

first_name | last_name | Search result
--------------------------------------
Bob        | Doe       | appears
--------------------------------------
Annie      | Doe       | excluded 
--------------------------------------
(null)     | Doe       | excluded 
--------------------------------------
John       | Foo       | appears 
--------------------------------------
(null)     | Foo       | appears 

到目前为止,我做的最好的是以下请求,但它不起作用:在我们的示例中,此请求将排除姓氏为 Doe 的所有人,无论名字如何……我不明白为什么?

GET user/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "last_name": "Doe"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "must": [
                    {
                      "terms": {
                        "first_name": [
                          "John",
                          "Annie"
                        ]
                      }
                    }
                  ]
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "first_name"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

非常感谢弹性敏锐眼的任何帮助!

标签: elasticsearchelasticsearch-query

解决方案


must_not 数组中的文档不得匹配任何子句。如果 last_name 是 Doe OR(first_name 是 annie 或 john 或不存在),您的查询基本上翻译为不考虑文档

工作并将您的查询放在 bool 中

{
  "query": {
    "bool": {
      "must_not": [
        {
          "bool": {
            "must": [
              {
                "match": {
                  "last_name": "Doe"
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "first_name.keyword": [
                          "John",
                          "Annie"
                        ]
                      }
                    },
                    {
                      "bool": {
                        "must_not": {
                          "exists": {
                            "field": "first_name"
                          }
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

推荐阅读