def build_query()

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


def build_query(term=None, categories=None, product_types=None, brands=None):
    must_query = (
        [{"match_all": {}}]
        if not term
        else [
            {
                "multi_match": {
                    "query": term,
                    "fields": ["name", "category", "description"],
                }
            }
        ]
    )

    filters = []
    if categories:
        filters.append({"terms": {"category": categories}})
    if product_types:
        filters.append({"terms": {"product_type": product_types}})
    if brands:
        filters.append({"terms": {"brand.keyword": brands}})

    return {
        "_source": [
            "id",
            "brand",
            "name",
            "price",
            "currency",
            "image_link",
            "category",
            "tag_list",
        ],
        "query": {"bool": {"must": must_query, "filter": filters}},
    }