Kirill Zaitsev
Kirill Zaitsev

Reputation: 4849

Elasticsearch get all parents with no children

Originally I've been trying to get a list of parents and a single most recent child for each one of them. I've figured how to do that with the following query

{"query": 
  {"has_child": 
    {"inner_hits": 
      {"name": "latest", "size": 1, "sort":
        [{"started_at": {"order": "desc"}}]
      }, 
     "type": "child_type", 
     "query": {"match_all": {}}
    }
  }
}

But the problem is — the results do not include parents with no children. Adding min_children: 0 doesn't help either. So I thought I could make a query for all parents with no children and combine those two in a single OR query. But I'm having trouble building such a query. Would appreciate any suggestions.

Upvotes: 3

Views: 3131

Answers (2)

puppylpg
puppylpg

Reputation: 1220

Another point: just use must_not for has_child will not only show parents without child, but all the child(s) as well, because they all don't have any child...

So another limitation should be added in the bool query:

{
  "query":{
    "bool": {
      "must_not": [
        {
          "has_child": {
            "type": "<child-type>",
            "query": {
              "match_all": {}
            }
          }
        }
      ],
      "should": [
        {
          "term": {
            "<the join field>": {
              "value": "<parent-type>"
            }
          }
        }
      ]
    }
  }
}

Upvotes: 1

Taras Kohut
Taras Kohut

Reputation: 2555

Here is your query:

    {
      "query":{
        "bool":{
          "should":[
            {
              "bool":{
                "must_not":[
                  {
                    "has_child":{
                      "type":"child_type",
                      "query":{
                        "match_all":{}
                      }
                    }
                  }
                ]
              }
            },
            {
              "has_child":{
                "inner_hits":{
                  "name":"latest",
                  "size":1, "sort":[{"started_at": {"order": "desc"}}]
                },
                "type":"child_type",
                "query":{
                  "match_all":{}
                }
              }
            }
          ]
        }
      }
    }

Upvotes: 5

Related Questions