Elasticsearch - Aggregations on part of bool query
Asked Answered
F

1

7

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!

Filagree answered 8/1, 2017 at 17:35 Comment(2)
Why you need to do that?Obsecrate
@Obsecrate Well I need all the people with first name Sandra, all the people with last name Jones and an aggregation on all the people with first name Sandra anyway, so I was wondering if I could merge them into a single query instead of two (all the people with first name Sandra + aggregation, and all the people with last name Jones). Just wishful thinking I guess.Filagree
H
9

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

Hollo answered 8/1, 2017 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.