Contains / in array in Azure Search (Preview)

大城市里の小女人 提交于 2020-01-14 09:46:08

问题


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?


回答1:


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')



来源:https://stackoverflow.com/questions/35153803/contains-in-array-in-azure-search-preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!