首页 > 解决方案 > 弹性搜索 ---:MUST_NOT 查询不起作用

问题描述

我有一个查询,我想在其中添加一个 must_not 子句,该子句将丢弃所有具有某个字段的空白数据的记录。我尝试了很多方法,但都没有奏效。当我使用其他特定字段发出相同的查询(如下所述)时,它可以正常工作。

此查询应获取所有没有“registrationType1”字段为空/空白的记录

query:
{
"size": 20,
"_source": [
"registrationType1"
],
"query": {
"bool": {
"must_not": [
{
"term": {
"registrationType1": ""
}
}
]
}
}
}

下面的结果仍然包含具有空值的“registrationType1”

results:

**"_source": {
"registrationType1": ""}}
, * {
"_index": "oh_animal",
"_type": "animals",
"_id": "3842002",
"_score": 1,
"_source": {
"registrationType1": "A&R"}}
, * {
"_index": "oh_animal",
"_type": "animals",
"_id": "3842033",
"_score": 1,
"_source": {
"registrationType1": "AMHA"}}
, * {
"_index": "oh_animal",
"_type": "animals",
"_id": "3842213",
"_score": 1,
"_source": {
"registrationType1": "AMHA"}}
, * {
"_index": "oh_animal",
"_type": "animals",
"_id": "3842963",
"_score": 1,
"_source": {
"registrationType1": ""}}
, * {
"_index": "oh_animal",
"_type": "animals",
"_id": "3869063",
"_score": 1,
"_source": {
"registrationType1": ""}}**

上述字段的 PFB 映射

"registrationType1": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}

标签: elasticsearch

解决方案


您需要使用keyword子字段来执行此操作:

{
  "size": 20,
  "_source": [
    "registrationType1"
  ],
  "query": {
    "bool": {
      "must_not": [
        {
          "term": {
            "registrationType1.keyword": ""       <-- change this
          }
        }
      ]
    }
  }
}

推荐阅读