elasticsearch must_not 返回错误值

elasticsearch must_not returning wrong values

我想弄清楚我的 Elastic 查询出了什么问题。我试图过滤掉所有标题为“软件工程师”的文档。我的查询:

{
  "from": 0,
  "size": 20,
  "query": {
    "bool": {
      "must": [{
        "bool": {
          "must_not": [{
            "term": {
              "title.keyword": "Software Engineer"
            }
          }]
        }
      }]
    }
  }
}

在我的映射中...

"title": {"type": "text"}

那么我的结果:

hits:[
{title: "Software Engineer"},
{title: "Engineer"},
{title: "Software Engineer"},
{title: "Software and Data Quality Manager"},
...
]

我不想在此处的搜索结果中找到软件工程师。任何帮助将不胜感激!

如果要将 title 字段映射为 textkeyword 类型,则需要使用 multi-fields。将您的索引映射修改为

{
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "fields": {
          "keyword": { 
            "type":  "keyword"
          }
        }
      }
    }
  }
}

索引数据:

{
  "title": "Software and Data Quality Manager"
}
{
  "title": "Software Engineer"
}
{
  "title": "Engineer"
}

搜索查询:

{
  "from": 0,
  "size": 20,
  "query": {
    "bool": {
      "must_not": {
        "term": {
          "title.keyword": "Software Engineer"
        }
      }
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "66064654",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.0,
        "_source": {
          "title": "Engineer"
        }
      },
      {
        "_index": "66064654",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.0,
        "_source": {
          "title": "Software and Data Quality Manager"
        }
      }
    ]

您的查询是正确的,默认情况下关键字是无操作分词器,因此请检查以确保您没有对索引和搜索时间中的关键字类型使用任何类型的标准化器,从而导致文本发生变化。如果您使用默认关键字,还请注意您的搜索将区分大小写,除非您在搜索和索引期间使用规范化程序。