Suraj Dalvi
Suraj Dalvi

Reputation: 1078

Elasticsearch must_not inside nested query

My elastic search index having nested fields. and I want to use must, which contains a must_not query in it with a nested query. I have tried a must_not query separately in the following way:

{
    "bool": {
        "must_not": [{
            "nested": {
                "path": "fields",
                "query": {
                    "terms": {
                        "fields.value.raw": [
                            "200"
                        ]
                    }
                }
            }
        }]
    }
}

above query gives me a valid result but when I was tried this with must query then it will not give me any result.I am using following query:

{
        "bool": {
            "must": [{
                "nested": {
                    "path": "fields",
                    "query": {
                        "bool": {
                            "must": [{
                                "match": {
                                    "fields.uid": "number"
                                }
                            }, {
                                "bool": {
                                    "must_not": [{
                                        "nested": {
                                            "path": "fields",
                                            "query": {
                                                "terms": {
                                                    "fields.value.raw": [
                                                        "200"
                                                    ]
                                                }
                                            }
                                        }
                                    }]
                                }
                            }]
                        }
                    }
                }
            }]
        }
    }

above query not gives me a valid result. What is wrong in above query? How I can use a must_not in must with nested query?

Upvotes: 0

Views: 2648

Answers (1)

Tarek Essam
Tarek Essam

Reputation: 4010

You should use must and must_not in the same bool query.

{
    "bool": {
        "must_not": [{
            "nested": {
                "path": "fields",
                "query": {
                    "terms": {
                        "fields.value.raw": [
                            "200"
                        ]
                    }
                }
            }
        }],
        "must": [{
            "match": {
                "fields.uid": "number"
            }
        }]
    }
}

Upvotes: 3

Related Questions