首页 > 解决方案 > 在对象数组中查找具有至少一个空值的文档

问题描述

我们的数据结构如下

{
    "foo": "bar",
    "baz": [
        {
            "qux": true
        },
        {
            "qux": null
        },
        {
            "qux": false
        }
    ]
}

在其他文档中,baz数组中的项目数可能会有所不同。

我们正在寻找在数组中至少具有一个null值的文档。quxbaz

我们尝试过:

{
    "query": {
        "bool": {
            "must_not": {
                "exists": {
                    "field": "baz.qux"
                }
            }
        }
    }
}

但是,这不会返回在数组中具有例如一个true和一个null值的文档。quxbaz

任何帮助将不胜感激!

标签: elasticsearch

解决方案


您可以使用嵌套映射嵌套查询来实现这一点。

映射:

{
    "properties": {
        "foo": {
            "type": "text"
        },
        "baz": {
            "type": "nested",
            "properties": {
                "qux": {
                    "type": "boolean"
                }
            }
        }
    }
}

询问:

{
    "query": {
        "nested": {
            "path": "baz",
            "query": {
                "bool": {
                    "must_not": {
                        "exists": {
                            "field": "baz.qux"
                        }
                    }
                }
            }
        }
    }
}

推荐阅读