How to search parent document without children?

I created parent-child relationship.

 "my_join_field": {
       "type": "join",
                "relations": {
                    "parent": "child"
                }
   }

I tried to search for all parent document without a child with this code

{
  "query": {
    "bool" : {
      "must_not" : {
        "has_child" : {
            "type": "child",
            "query": {
                "match_all": {}
            }
        }
      }
    }
  },
  "size": 10
}

And it returns child records and incorrect result because the result return contain child with the parent

Need advice on how to search parent documents without children and the result return is parent document?

See if this helps: https://stackoverflow.com/questions/41283486/elasticsearch-get-all-parents-with-no-children/41285084#41285084

Hi Lyudmila_Fokina,

Thank you for your help.

I checked the link and the articles problem want to get

  • list of parents and a single recent child OR
  • list of parents without a child

If I remove the list of parents and a single recent child query, the query is the same as the one I share above based on the link you shared

Not able to get the parent with no child

Try this one (worked for me);
{
"query": {
"bool" : {
"must" : [ {
"bool" : {
"must_not" : {
"has_child" : {
"type": "child",
"query": {
"match_all": {}
}
}
}
}
},
{
"match": {
"relation_type": "parent"
}
}]
}
},
"size": 10
}

1 Like

Hi Lyudmila_Fokina,

You just save my life. :+1: :+1: :+1: The query you shared is working.
Now the result returns the parent document when there no children as I want to delete all the parent resume that not longer contain children.

(is there a better way to delete parent doc without retrieve, loop, and delete ?)
like one API call that helps clean up will be awesome if exist)

I changed the 2nd query to make it happen as the"relation_type" field is not working.
The "relation_type" you shared suppose to change to "my_join_field"?

"match": {
   "my_join_field": "###parent###"
}

Full working query

{
    "query": {
        "bool": {
            "must": [
                {
                    "bool": {
                        "must_not": {
                            "has_child": {
                                "type": "###child###",
                                "query": {
                                    "match_all": {}
                                }
                            }
                        }
                    }
                },
                {
                    "match": {
                        "my_join_field": "###parent###"
                    }
                }
            ]
        }
    },
    "size": 10
}

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