Search code examples
c#azure-cognitive-searchasp.net-core-2.2

Azure Search Using Multiple filters


I have three filters namely category, subcategory and product type that need to be applied to the search query. I am currently using Azure Search.As of now, I am using odata filter as shown in the code below.

SearchParameters parameters = new SearchParameters();

        string searchText = Request.Query["query"];
        string category = Request.Query["c"];
        string subCategory = Request.Query["sc"];
        string productType = Request.Query["pt"];

        parameters.Filter = $"Category/Id eq '{category}' or SubCategory/Id eq '{subCategory}'" +
                              $"or ProductType/Id eq '{productType}'";

How can I obtain a result in which if the user applies categoryId, then it should display results pertaining to that Category Id.If the user applies both categoryId and subcategoryId, he should be able to see both products that matches with the specified filter category and subcategory.If only submits producttypeId then he should be able to see products pertaining to that producttypeId. Of Course , I could use if and else and build my filter using 'logical or' and 'logical and'. If there is any Odata Library that would help me in this regard?


Solution

  • Thanks for the suggestion.I worked a way around this thing using OData FilterString

     string filterquery = FilterString.Generate<Product>(p => p.Category.Id == category && 
                p.SubCategory.Id == subCategory &&                            
                p.ProductType.Id == productType);
    
     parameters.Filter = filterQuery;