有没有一种方法可以区分字段不存在时和字段存在但为空时({})

wixjitnu  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(575)

我有两种文件:

"doc1":{
    "dummy_attribute":"HI",
    ...
    "important_attribute":{}
}
"doc2":{
    "dummy_attribute":"HI",
    ...
}

如果我这样搜索:

GET myindex/_search
{
  "query": {
    "bool": {
      "must_not": [{
        "exists": {
          "field": "important_attribute"
        }
      }]
    }
  }
}

它还给我两份文件。有没有办法只搜索文档中实际上不存在“重要属性”的文档?

xytpbqjk

xytpbqjk1#

不幸的是,这是不可能的,因为es将不存在的值视为空值( null , "" , [] 或者 {} ).
可以使用脚本字段快速检查文档是否包含空的dict,但在筛选时不能使用此上下文:

GET myindex/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "important_attribute"
          }
        }
      ]
    }
  },
  "script_fields": {
    "has_empty_dict": {
      "script": {
        "source": "params._source.containsKey('important_attribute') && params._source.important_attribute.size() == 0"
      }
    }
  }
}

相关问题