Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch - Aggregations on part of bool query

Say I have this bool query:

"bool" : {
    "should" : [
        { "term" : { "FirstName" : "Sandra" } },
        { "term" : { "LastName" : "Jones" } }
     ],
     "minimum_should_match" : 1
}

meaning I want to match all the people with first name Sandra OR last name Jones.

Now, is there any way that I can get perform an aggregation on all the documents that matched the first term only?

For example, I want to get all of the unique values of "Prizes" that anybody named Sandra has. Normally I'd just do:

"query": {
    "match": {
        "FirstName": "Sandra"
    }
},
"aggs": {
    "Prizes": {
        "terms": {
            "field": "Prizes"
        }
    }
}

Is there any way to combine the two so I only have to perform a single query which returns all of the people with first name Sandra or last name Jones, AND an aggregation only on the people with first name Sandra?

Thanks alot!

like image 645
dan martin Avatar asked Jan 08 '17 17:01

dan martin


1 Answers

Use post_filter. Please refer the following query. Post_filter will make sure that your bool should clause don't effect your aggregation scope.

Aggregations are filtered based on main query as well, but they are unaffected by post_filter. Please refer to the link

{
    "from": 0,
    "size": 20,
    "aggs": {
        "filtered_lastname": {
            "filter": {
                "query": {
                    "match": {
                        "FirstName": "sandra"
                    }
                }
            },
            "aggs": {
                "prizes": {
                    "terms": {
                        "field": "Prizes",
                        "size": 10
                    }
                }
            }
        }
    },
    "post_filter": {
        "bool": {
            "should": [{
                "term": {
                    "FirstName": "Sandra"
                }
            }, {
                "term": {
                    "LastName": "Jones"
                }
            }],
            "minimum_should_match": 1
        }
    }
}

Running a filter inside the aggs before aggregating on prizes can help you achieve your desired usecase.

Thanks Hope this helps

like image 195
user3775217 Avatar answered Sep 20 '22 14:09

user3775217