0
votes

I have built a parent-child mapping in ES for companies and employees.

I can successfully execute the following query to find children with a match on a parent company field:

{
    "query": {
        "has_parent": {
            "parent_type": "company",
            "query": {
                "match": {
                    "company_name": "stackoverflow"
                }
            }
        }
    }
}

What I can't figure out is how to enhance this to query on a child employee field at the same time:

{
    "query": {
        "match": {
            "job_title": "CEO"
        }
    }
}

I want back children that have a parent company_name of stackoverflow AND a child job_title of CEO.

How can I write a query that filters on both parent AND child fields?

1

1 Answers

0
votes

The trick is to build the two queries into a filter or similar:

{
    "query": {
        "bool": {
            "filter": [
                {
                    "has_parent": {
                        "parent_type": "company",

                        //Query on the parent

                        "query": {
                            "match": {
                                "company_name": "stackoverflow"
                            }
                        }
                    }
                },
                {

                   //Query on the child

                    "bool": {
                        "should": [
                            {
                                "match": {
                                    "job_title": {
                                        "query": "CEO"
                                    }
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}