Search code examples
c#azureluceneazure-cognitive-searchazure-search-.net-sdk

Azure Search SDK fails partial search when using special characters


I have a below code which should return all the names starting with T&S from azure index for example the results should be like below

  • T&S
  • T&S Limited
  • T&S Corporation

The search text we see in the code is the UrlEncoded version of "T&S*"

Search Code Block

   var response = await _searchClient.Documents.SearchAsync<customDto>("%22T%26S%22*",
            new SearchParameters
            {
                SearchFields = new List<string> { "Name" },
                SearchMode = SearchMode.All
            });

Custom DTO

   public class CustomDto{
          public CustomDto(int id,string name)
          {
             Id=Convert.ToString(id),
             Name=name
          }

          [IsSearchable, IsFilterable]
          [System.ComponentModel.DataAnnotations.Key]
          public string Id { get; }

          [IsSearchable, IsFilterable, IsSortable]
          public string Name {get;}

   }

Now, If i put the similar search text on the azure search query window i get results as expected %22T%26S%22*&searchMode=all&searchFields=Name

But for some reason the code returns empty result. I dont get what am i doing wrong here.

Please assist.

Thank you


Solution

  • Can you try with the following code. This uses Microsoft.Azure.Search SDK (version 10.1.0).

            var searchCredentials = new SearchCredentials("<api-key (admin or query>");
            var indexClient = new SearchIndexClient("<search-service-name>", "<index-name>", searchCredentials);
            var results = indexClient.Documents.Search("\"T\\&S\"*",
            new SearchParameters
            {
                SearchFields = new List<string> { "Name" },
                SearchMode = SearchMode.All
            });
    

    SDK actually makes a POST request so you don't really have to URL encode the search string (you would need to do that when you issue a GET request). What you need to do is escape & character by prefixing it with a \ and that's what I did. Please see Escaping Special Characters here: https://learn.microsoft.com/en-us/azure/search/query-lucene-syntax#bkmk_syntax for more information.