首页 > 解决方案 > 在弹性搜索中搜索具有空/空对象字段的文档

问题描述

我有一个带有以下映射的弹性搜索索引,一些文档包含状态为 {id:1, status:"failed"} 的对象,有些为空,似乎无法找到一种方法来搜索具有“status.name”的文档["failed", "null", "passed"] (其中任一状态为失败、通过或未设置/null 的文档)。例如,像下面这样进行术语查询会给出空结果集

{
"name":{
"type":"keyword"
}
 "status": {
                "properties": {
                    "id": {
                        "type": "integer"
                    },
                    "status": {
                        "type": "keyword"
                    }
                }
            }
}

查询尝试:

{
"terms": {
  "status.name": [  "failed", "null" ]
   }

还尝试将 status.name 的映射设置为"null_value": "null"

标签: elasticsearch

解决方案


仅使用带有 should 子句的 bool 查询,要求至少有一个查询必须匹配。exists您可以通过将-query 放入must_not-query 的 - 子句中来查询没有字段或在该字段中具有空值的文档bool(请参阅 Elasticsearch 参考:Exists-query)。

GET myindex/_search
{
  "query": {
    "bool": {
      "should": [
        {"term": {"status.name": {"value": "failed"}}},
        {"term": {"status.name": {"value": "passed"}}},
        {"bool": {"must_not": {"exists": {"field": "status.name"}}}}
      ]
    }
  }
}

推荐阅读