Escaping Characters in Azure Search

No comments

If you are new to Azure Search, you must make sure to escape certain characters in Sitecore Search queries. Currently, Azure search or the Sitecore Content search api does not escape these characters.

{“error”:{“code”:””,”message”:”Invalid expression: ‘)’ or ‘,’ expected at position 102 in ‘((taxonomy/any(t:t eq ‘language/english’)) and (taxonomy/any(t:t eq ‘customer name/italy/test delaarte)) and (taxonomy/any(t:t eq ‘asset type/document’)) and (taxonomy/any(t:t eq ‘audience/external’)))’.\r\nParameter name: $filter”}}

Description: An unhandled exception occurred. 

Exception Details: Sitecore.ContentSearch.Azure.Http.Exceptions.AzureSearchServiceRESTCallException: {“error”:{“code”:””,”message”:”Invalid expression: ‘)’ or ‘,’ expected at position 102 in ‘((taxonomy/any(t:t eq ‘language/english’)) and (taxonomy/any(t:t eq ‘customer name/country/test delaarte‘)) and (taxonomy/any(t:t eq ‘asset type/document’)) and (taxonomy/any(t:t eq ‘audience/external’)))’.\r\nParameter name: $filter”}}

Source Error: 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 

[AzureSearchServiceRESTCallException: {“error”:{“code”:””,”message”:”Invalid expression: ‘)’ or ‘,’ expected at position 102 in ‘((taxonomy/any(t:t eq ‘language/english’)) and (taxonomy/any(t:t eq ‘customer name/country/test dela’arte’)) and (taxonomy/any(t:t eq ‘asset type/document’)) and (taxonomy/any(t:t eq ‘audience/external’)))’.\r\nParameter name: $filter”}}]

[BadRequestException: Error in the request URI, headers, or body]
Sitecore.ContentSearch.Azure.Http.SearchServiceClient.EnsureSuccessStatusCode(HttpResponseMessage response) +590
Sitecore.ContentSearch.Azure.Http.SearchServiceClient.Search(SearchRequest searchRequest) +704
Sitecore.ContentSearch.Azure.Http.SearchServiceClient.Search(String expression) +171
Sitecore.ContentSearch.Azure.Query.LinqToCloudIndex`1.Execute(CloudQuery query, Int32& countDoc, Int32& totalDoc, Dictionary`2& facetResult, SearchRequest& nextPageRequestParameters) +2632
Sitecore.ContentSearch.Azure.Query.LinqToCloudIndex`1.Execute(CloudQuery compositeQuery) +277
Sitecore.ContentSearch.Linq.QueryableExtensions.GetResults(IQueryable`1 source) +381
lambda_method(Closure , ControllerBase , Object[] ) +87
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
System.Web.Mvc.<>c__DisplayClass24_0.<InvokeActionMethodWithFilters>b__0() +80
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +454
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +454
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +524



These are the characters that have to be escaped (as mentioned in official documentation):

Unsafe characters are " ` < > # % { } | \ ^ ~ [ ].

Reserved characters are  ; / ? : @ = + &

The customer name in above query contains a single quotes that has to be escaped with ‘\’ test dela’arte –> test dela\’arte

Write a simple function replace below set of characters in search query string.

        /// <summary>
        /// Escaping Characters in Azure
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
private string EscapeCharatersInQuery(string query)
        {
           string[] specialCharactersInAzure = {"'",
            "+", "-","=", "&&", "||", "!", "{", "}", "[", "]", "^", "~", "*", "?", ":","\"","\\","`",";","@"};
            foreach (var str in specialstringsInAzure)
                query = query.Replace(str, "\\" + str);

            return query;
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.