Contains / in array in Azure Search (Preview)
Asked Answered
D

1

7

I am using the new (preview) Azure Search SDK (information here). I am using the oData expression syntax to build up my search query using the $filter parameter and I would like to be able to feed across an array of ids to the endpoint. The brandId field is in my Azure Search Index and it is searchable, filterable, sortable, and facetable. Ideally I would like to be able to do something along the lines of:

http://host/service/Products?brands=["1","2"]

(See specification here under the section entitled "Complex and Collection Literals")

I can't figure out what syntax to use to include the collection literal syntax inside of the $filter query. So I'm currently just string concatenating loads of logical ORs together to form the query instead which is less than ideal:

var sp = new SearchParameters();

string filter = "$filter=";

if(brands.Length > 0)
{   
    int counter = 0;

    foreach(string brand in brands)
    {
        if(counter == 0)
        {
            filter += "(brandId eq '" + brand + "'";
        }   
        else if(counter == (brands.Count() - 1))
        {
            filter += " or brandId eq '" + brand + "')";
        }
        else
        {
            filter += " or brandId eq '" + brand + "'";
        }
        counter++;
    }
}

sp.Filter = filter;

DocumentSearchResult response = indexClient.Documents.Search(theSearchQuery, sp);

foreach(SearchResult result in response.Results)
{
    // do stuff to the results

}

The final (url-encoded) URI comes out as:

https://[mysearchservicename].search.windows.net/indexes/products/docs?api-version=2015-02-28&$filter=language%20eq%20%27us%27%20and%20%28brandId%20eq%20%276%27%20or%20brandId%20eq%20%278%27%20or%20brandId%20eq%20%279%27%20or%20brandId%20eq%20%2710%27%20or%20brandId%20eq%20%2711%27%20or%20brandId%20eq%20%2713%27%20or%20brandId%20eq%20%2722%27%29

Was hoping someone could enlighten me?

Defame answered 2/2, 2016 at 12:40 Comment(0)
G
8

Azure Search doesn't support collection literals or parameterized filters, but it does offer a specialized function for this case: search.in. The subset of OData supported by Azure Search, as well as the search.in function, are documented here.

Here's an example of how you would use search.in for this specific case:

$filter=search.in(brandId, '1,2')

Gaylor answered 2/2, 2016 at 18:37 Comment(4)
Thanks for the heads up!Defame
I think this answer may be outdated nowCaptor
@JamesReategui, can you provide a more up-to-date answer instead, please?Piles
I wrote the answer (and the code that implements filters in Azure Cognitive Search), and the answer is still up-to-date from my perspective.Gaylor

© 2022 - 2024 — McMap. All rights reserved.