[Query DSL] Get documents which don't have a sepcific value (in array, object/nested)

I will explain with examples, it should be better.

I have 3 documents A, B and C (to be precise, in fact it's 3 type of document, there is more documents)
Each document has a nested field of objects (with some fields), and I would like to query the documents to get all document which don't have a sub-object field in the nested field ("nestedfield") with a specific value.

Example:

{
	"_id": "A",
	"_source": {
		"somefields": "somevalues",
		"nestedfield": [
			{
				"id": "U1",
				"type": "T1",
			},
			... //Can be more (but no type "T2")
		]
	}
}
{
	"_id": "B",
	"_source": {
		"somefields": "somevalues",
		"nestedfield": [
			{
				"id": "U2",
				"type": "T1",
			},
			{
				"id": "U3",
				"type": "T2",
			},
			... //Can be more
		]
	}
}
{
	"_id": "C",
	"_source": {
		"somefields": "somevalues",
		"nestedfield": null //means no element in the list
	}
}

On this documents, I'm trying to get all documents which doesn't have at least one nestedfield.type "T2" => doc A & C (or at least A, due to C being considered as unmapped)

Here is the query I began to work on.

{
    "query": {
        "bool": {
            "should": [
                {
                    "nested": {
                        "path": "nestedfield",
                        "query": {
                            "bool": {
                                "must_not": [
                                    {
                                        "term": {
                                            "nestedfield.type.raw": {
                                                "value": "T2"
                                            }
                                        }
                                    }
                                ]
                            }
                        },
                        "ignore_unmapped": true
                    }
                },
                {
                    "bool": {
                        "must_not": {
                            "exists": {
                                "field": "nestedfield"
                            }
                        }
                    }
                }
            ]
        }
    }
}

Notes :

  • current elasticsearch version : 7.9

Thanks for reading.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.