1

Does anyone have an example of getting the Answer from the semantic search in Azure Cognitive Search using c#.

This is what I have but I can seem to get the AnswerResult from it.

    SearchOptions options;
    SearchResults<Hotel> response;

   

    options = new SearchOptions()
    {
        QueryType = Azure.Search.Documents.Models.SearchQueryType.Semantic,
        QueryLanguage = QueryLanguage.EnUs,
        SemanticConfigurationName = "my-semantic-config",
        QueryCaption = QueryCaptionType.Extractive,
        QueryCaptionHighlightEnabled = true
    };
    options.Select.Add("HotelName");
    options.Select.Add("Category");
    options.Select.Add("Description");

    // response = srchclient.Search<Hotel>("*", options);
    response = srchclient.Search<Hotel>("Who is the manager of Triple Landscape Hotel?", options);

I have tried and can see the answer in rest but I am a bit of of newbie to using it C#

  • Welcome to Stack Overflow! When you say `can see the answer in rest`, do you mean that the `reponse` variable is being populated with the correct response but you're not sure how to use it? Or are you able to call the API by another means and get the correct response but your C# code does not receive the correct response? It would also help if you could include the code for creating `srchclient` in your question. – sbridewell Jun 23 '23 at 18:35

1 Answers1

1

In order to access the Semantic Answer using the .NET SDK for Azure Cognitive Search, you have to pass QueryAnswer = QueryAnswerType.Extractive to your SearchOptions. Then you can loop through the Answers property like this:

First, update your SearchOptions:

options = new SearchOptions()  
{  
    // Other options...  
    QueryAnswer = QueryAnswerType.Extractive // Add this line to enable query answer  
};

Next, loop through the extractive answers in the response.Answers dictionary after performing the search:

if (response.Answers != null && response.Answers.TryGetValue("extractive", out var extractiveAnswers))  
{  
    Console.WriteLine("Query Answer:");  
    foreach (AnswerResult result in extractiveAnswers)  
    {  
        Console.WriteLine($"Answer Highlights: {result.Highlights}");  
        Console.WriteLine($"Answer Text: {result.Text}\n");  
    }  
} 

This code checks if response.Answers is not null and retrieves extractive answers before looping through them.

Farzzy - MSFT
  • 290
  • 1
  • 10