Elasticsearch排除多个术语的关联



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

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

预期结果示例:

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"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Elastic敏锐的眼睛对此的任何帮助都将不胜感激!

在must_not数组中,文档不能与任何子句匹配。如果last_name是Doe或(first_name是annie或john或不存在(,则您的查询基本上转化为不考虑文档

要作为AND工作,请将您的查询放在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"
                          }
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

最新更新