0

I have a web app API which using ACS V11 SDK to search index documents and return the search results. Bellow is simplified code in my API interface:

public async Task<SearchResults<SearchDocument>> SearchIndexDocumentsAsync(
            [FromBody] SearchParameters parameters,
            CancellationToken cancellationToken = default)
        {
            var searchIndexClient = new SearchIndexClient(
                                            new Uri(endpoint),
                                            new AzureKeyCredential(apiKey));

            var searchClient = searchIndexClient.GetSearchClient(indexName);

            SearchResults<SearchDocument> docs = await searchClient.SearchAsync<SearchDocument>(parameters.Query, searchOptions: null, cancellationToken).ConfigureAwait(false);
            
            return docs;
        }

The problem is, the response Json only contains total count, but no document results, like below:

{
  "totalCount": 19
}

I know I can iterate all documents from ACS SDK response and add them to a list like this:

   var results = new List<SearchResult<SearchDocument>>();

   await foreach (SearchResult<SearchDocument> document in docs.GetResultsAsync())
   {
       results.Add(document);
   }

   return results;

But is there any easier way to return the full search results including documents without having to iterate all document?

Youxu
  • 1,050
  • 1
  • 9
  • 34

1 Answers1

0

One possible to this, is by returning Response<SearchResults<SearchDocument>>instead of returning SearchResults<SearchDocument>.

This way, you return the entire response object, which includes the search result.

I have used this in below code snippet:

static async Task Main(string[] args)
    {
        var searchIndexClient = new SearchIndexClient(
                                    new Uri(endpoint),
                                    new AzureKeyCredential(apiKey));

        var searchClient = searchIndexClient.GetSearchClient(indexName);

        string query = "Sample";
        Response<SearchResults<SearchDocument>> response = await searchClient.SearchAsync<SearchDocument>(query);
                
        string jsonResponse = JsonConvert.SerializeObject(response.Value.GetResults(), Formatting.Indented);
        Console.WriteLine(jsonResponse);

With the above code snippet, I was able to get all the result documents. enter image description here

RishabhM
  • 525
  • 1
  • 5
  • Thanks RishabhM. However, the SearchResults> contains not only the document list, but also Facets, the response.Value.GetResults() return SearchResult which only contains list of documents. – Youxu Aug 10 '23 at 20:23