Getting the AnswerResult from Azure Cognitive Search

316 views Asked by At

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#

1

There are 1 answers

0
Farzzy - MSFT On BEST ANSWER

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.