简体   繁体   中英

elasticsearch - how to aggregate and filter by multiple rows

I have the following data.

在此处输入图片说明

How can I query all countries that have currency 1 and 2?

The country can have multiple rows with the same currency (so count, can't help)

You should filter queries by desired currencies and aggregate them with a term aggregation.
The tricky part is force Elasticsearch to get all possible countries. This can be done using size=0 parameter in terms aggregation

currencies_criteria = [1,2]

elasticsearch_query = {
    "query": {
        "filtered": {
            "filter": {
                "bool": {
                    "must" : [
                        {
                            "term": {"currency" : currencies_criteria}
                        }
                    ]

                }
            }
        }
    },
    "aggs" : {
        "country_count" : {
            "terms" : {
                "field" : "country",
                #https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-approximate-counts
                "size"  : 0
            }
        }
    }
}

You can see the sample execution of this answer in this notebook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM