def get_facets_data()

in supporting-blog-content/hybrid-search-for-an-e-commerce-product-catalogue/product-store-search/api/api.py [0:0]


def get_facets_data(term, categories=None, product_types=None, brands=None):
    query = build_query(term, categories, product_types, brands)
    query["aggs"] = {
        "product_types": {"terms": {"field": "product_type"}},
        "categories": {"terms": {"field": "category"}},
        "brands": {"terms": {"field": "brand.keyword"}},
    }
    response = get_client_es().search(index="products-catalog", body=query, size=0)

    return {
        "product_types": [
            {"product_type": bucket["key"], "count": bucket["doc_count"]}
            for bucket in response["aggregations"]["product_types"]["buckets"]
        ],
        "categories": [
            {"category": bucket["key"], "count": bucket["doc_count"]}
            for bucket in response["aggregations"]["categories"]["buckets"]
        ],
        "brands": [
            {"brand": bucket["key"], "count": bucket["doc_count"]}
            for bucket in response["aggregations"]["brands"]["buckets"]
        ],
    }