Yash Tandon
Yash Tandon

Reputation: 475

How do i disqualify a parent document based on a key value pair in a child doc in elasticsearch

I am using parent child relationship in elasticsearch v7.3 suppose my parent document consist of 'users' also their are more than one child documents for each parent document. Now in all my child document i have with me a text field suppose 'name' with value 'raju' or 'yash' or etc. And my query is to get all the parent documents, whose child doc must not contain 'name' equals to 'raju'.

i.e if suppose we have 4 child doc in a parent doc and even if one child doc has name 'raju' then its parent doc must be disqualified and it must not be retrieved. hence i would request if anyone can help me with this.

                "has_child": {
                  "type": "child_1",
                  "query": [
                    {
                      "bool": {
                        "must_not": [
                          {
                            "match_phrase": {
                              "name": "raju"
                            }
                          }
                        ]
                      }
                    }
                  ]
                }

Upvotes: 0

Views: 53

Answers (1)

Pierre Mallet
Pierre Mallet

Reputation: 7221

You should inverse your query logic. The must_not clause should be on the parent side.

Could you test something like :

{
    "query": {
        "bool": {
            "filter": [
                {
                    "has_child": {
                        "type": "child_1",
                        "query": {
                            "match_all": {}
                        },
                        "score_mode": "none"
                    }
                }
            ],
            "must_not": [
                {
                    "has_child": {
                        "type": "child_1",
                        "query": {
                            "match_phrase": {
                                "name": "raju"
                            }
                        },
                        "score_mode": "none"
                    }
                }
            ]
        }
    }
}

NB : the filter clauses ensure returned document are parent document as pointed out in the comments

Upvotes: 1

Related Questions