1

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

Sike12
  • 1,232
  • 6
  • 28
  • 53
  • Why are you URL Encoding it? My guess is that SDK is again encoding what you're sending so the search string is being encoded twice. I would recommend checking the request/response through Fiddler to confirm this behavior. – Gaurav Mantri Jun 05 '20 at 10:40
  • @GauravMantri-AIS SDK doesnt url encode for you. we have to do it ourselves. – Sike12 Jun 05 '20 at 10:56
  • Oh! That's weird. I thought SDK would be smart enough to do this :). What do you see in Fiddler? As in what's the request being sent to the service? – Gaurav Mantri Jun 05 '20 at 11:00
  • I see the exact param value i.e %22T%26S%22* It would be nice Gaurav if this was handled automatically. – Sike12 Jun 05 '20 at 11:05

1 Answers1

2

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.

Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241