Compartilhar via


Início Rápido: Classificação semântica

Neste início rápido, você aprenderá a usar a classificação semântica adicionando uma configuração semântica a um índice de pesquisa e adicionando parâmetros semânticos a uma consulta. Você pode usar o índice de exemplo de hotéis (hotels-sample-index) ou um dos seus.

No Azure AI Search, a classificação semântica é a funcionalidade do lado da consulta que usa a compreensão de leitura de computador da Microsoft para pontuar os resultados da pesquisa, promovendo as correspondências mais semanticamente relevantes para o topo da lista. Dependendo do conteúdo e da consulta, a classificação semântica pode melhorar significativamente a relevância da pesquisa com o mínimo de esforço do desenvolvedor.

Você pode adicionar uma configuração semântica a um índice existente sem nenhum requisito de recompilação. A classificação semântica é mais eficaz em texto informativo ou descritivo.

Pré-requisitos

Configurar o acesso

É possível se conectar ao serviço Pesquisa de IA do Azure usando as chaves de API ou o Microsoft Entra ID com atribuições de função. É mais fácil usar as chaves para começar, mas as funções são mais seguras. Para obter mais informações, confira Conectar-se à Pesquisa de IA do Azure usando funções.

Para configurar o acesso baseado em função:

  1. Entre no portal do Azure e selecione seu serviço de pesquisa.

  2. No painel à esquerda, selecione Configurações>Chaves.

  3. No Controle de Acesso à API, selecione Controle de Acesso Baseado em Função ou Ambos se precisar de tempo para fazer a transição de clientes para acesso baseado em função.

  4. No painel esquerdo, selecione Controle de acesso (IAM).

  5. Selecione Adicionar>Adicionar atribuição de função.

  6. Atribua as funções de Colaborador do Serviço de Pesquisa e Colaborador de Dados do Índice de Pesquisa à sua conta de usuário.

Começar com um índice

Este início rápido pressupõe um índice existente e o modifica para incluir uma configuração semântica. Recomendamos o índice de exemplo de hotéis que você pode criar em minutos usando um assistente do portal do Azure.

Para começar com um índice existente:

  1. Entre no portal do Azure e localize seu serviço de pesquisa.

  2. EmGerenciamento de Pesquisa>Índices, selecione o hotéis-sample-index.

  3. Selecione configurações semânticas para garantir que o índice não tenha uma configuração semântica.

    Captura de tela de uma página de configuração semântica vazia no portal do Azure.

  4. Selecione o Gerenciador de Pesquisa e, em seguida, selecione o modo de exibição JSON.

  5. Cole os dados JSON abaixo no editor de consultas.

    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true
    }
    

    Captura de tela de uma consulta no Gerenciador de Pesquisa no portal.

  6. Selecione Pesquisar para executar a consulta.

    Essa consulta é uma pesquisa de palavra-chave. A resposta deve ser semelhante ao exemplo a seguir, conforme pontuação pelo classificador BM25 L1 padrão para pesquisa de texto completo.

    Para garantir a legibilidade, o exemplo seleciona apenas os campos HotelId, HotelName, e Description. Os resultados contêm correspondências verbais nos termos da consulta (walking, , distance, live) musicou variantes linguísticas (walk, living).

    "@odata.count": 13,
    "value": [
      {
        "@search.score": 5.5153193,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
      },
      {
        "@search.score": 5.074317,
        "HotelId": "24",
        "HotelName": "Uptown Chic Hotel",
        "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
      },
      {
        "@search.score": 4.8959594,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
      },
      {
        "@search.score": 2.5966604,
        "HotelId": "35",
        "HotelName": "Bellevue Suites",
        "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport."
      },
      {
        "@search.score": 2.566386,
        "HotelId": "47",
        "HotelName": "Country Comfort Inn",
        "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome."
      },
      {
        "@search.score": 2.2405157,
        "HotelId": "9",
        "HotelName": "Smile Up Hotel",
        "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene."
      },
      {
        "@search.score": 2.1737604,
        "HotelId": "8",
        "HotelName": "Foot Happy Suites",
        "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further."
      },
      {
        "@search.score": 2.0364518,
        "HotelId": "31",
        "HotelName": "Country Residence Hotel",
        "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
      },
      {
        "@search.score": 1.7595702,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
      },
      {
        "@search.score": 1.5502293,
        "HotelId": "15",
        "HotelName": "By the Market Hotel",
        "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
      },
      {
        "@search.score": 1.3302404,
        "HotelId": "42",
        "HotelName": "Rock Bottom Resort & Campground",
        "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away."
      },
      {
        "@search.score": 0.9050383,
        "HotelId": "38",
        "HotelName": "Lakeside B & B",
        "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
      },
      {
        "@search.score": 0.7334347,
        "HotelId": "39",
        "HotelName": "White Mountain Lodge & Suites",
        "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
      }
    ]
    

Esta consulta mostra a aparência da resposta antes da classificação semântica ser aplicada. Posteriormente, você pode executar a mesma consulta depois que a classificação semântica é configurada para ver como a resposta muda.

Dica

Você pode adicionar uma configuração semântica no portal do Azure. No entanto, se você quiser aprender a adicionar uma configuração semântica programaticamente, continue com este início rápido.

Configurar o cliente

Neste início rápido, você usará um IDE e a biblioteca de clientes do Azure.Search.Documents para adicionar classificação semântica a um índice de pesquisa existente.

Recomendamos o Visual Studio para este início rápido.

Dica

É possível baixar o código-fonte para começar com um projeto concluído, ou seguir as etapas neste artigo para criar o seu.

Instalar bibliotecas

  1. Inicie o Visual Studio e abra o quickstart-semantic-search.sln ou crie um novo projeto usando um modelo de aplicativo de console.

  2. Em Ferramentas>Gerenciador de Pacotes NuGet, selecione Gerenciar Pacotes NuGet para a Solução....

  3. Selecione Procurar.

  4. Pesquise pelo pacote do Azure.Search.Documents e selecione a versão estável mais recente.

  5. Pesquise o pacote Azure.Identity e selecione a versão estável mais recente.

  6. Selecione Instalar para adicionar o assembly ao projeto e à solução.

Entrar no Azure

Se você entrou no portal do Azure, está conectado ao Azure. Se você não tiver certeza, use a CLI do Azure ou o Azure PowerShell para fazer logon: az login ou az connect. Se você tiver vários locatários e assinaturas, consulte Início Rápido: Conectar sem chaves para obter ajuda sobre como se conectar.

Atualizar o índice

Nesta seção, você atualizará um índice de pesquisa para incluir uma configuração semântica. O código obtém a definição de índice do serviço de pesquisa e adiciona uma configuração semântica.

  1. Abra o projeto BuildIndex no Visual Studio. O programa consiste no código a seguir.

    Esse código usa um SearchIndexClient para atualizar um índice em seu serviço de pesquisa.

    class BuildIndex
    {
        static async Task Main(string[] args)
        {
            string searchServiceName = "PUT-YOUR-SEARCH-SERVICE-NAME-HERE";
            string indexName = "hotels-sample-index";
            string endpoint = $"https://{searchServiceName}.search.windows.net";
            var credential = new Azure.Identity.DefaultAzureCredential();
    
            await ListIndexesAsync(endpoint, credential);
            await UpdateIndexAsync(endpoint, credential, indexName);
        }
    
        // Print a list of all indexes on the search service
        // You should see hotels-sample-index in the list
        static async Task ListIndexesAsync(string endpoint, Azure.Core.TokenCredential credential)
        {
            try
            {
                var indexClient = new Azure.Search.Documents.Indexes.SearchIndexClient(
                    new Uri(endpoint),
                    credential
                );
    
                var indexes = indexClient.GetIndexesAsync();
    
                Console.WriteLine("Here's a list of all indexes on the search service. You should see hotels-sample-index:");
                await foreach (var index in indexes)
                {
                    Console.WriteLine(index.Name);
                }
                Console.WriteLine(); // Add an empty line for readability
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error listing indexes: {ex.Message}");
            }
        }
    
        static async Task UpdateIndexAsync(string endpoint, Azure.Core.TokenCredential credential, string indexName)
        {
            try
            {
                var indexClient = new Azure.Search.Documents.Indexes.SearchIndexClient(
                    new Uri(endpoint),
                    credential
                );
    
                // Get the existing definition of hotels-sample-index
                var indexResponse = await indexClient.GetIndexAsync(indexName);
                var index = indexResponse.Value;
    
                // Add a semantic configuration
                const string semanticConfigName = "semantic-config";
                AddSemanticConfiguration(index, semanticConfigName);
    
                // Update the index with the new information
                var updatedIndex = await indexClient.CreateOrUpdateIndexAsync(index);
                Console.WriteLine("Index updated successfully.");
    
                // Print the updated index definition as JSON
                var refreshedIndexResponse = await indexClient.GetIndexAsync(indexName);
                var refreshedIndex = refreshedIndexResponse.Value;
                var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
                string indexJson = JsonSerializer.Serialize(refreshedIndex, jsonOptions);
                Console.WriteLine($"Here is the revised index definition:\n{indexJson}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error updating index: {ex.Message}");
            }
        }
    
        // This is the semantic configuration definition
        static void AddSemanticConfiguration(SearchIndex index, string semanticConfigName)
        {
            if (index.SemanticSearch == null)
            {
                index.SemanticSearch = new SemanticSearch();
            }
            var configs = index.SemanticSearch.Configurations;
            if (configs == null)
            {
                throw new InvalidOperationException("SemanticSearch.Configurations is null and cannot be assigned. Your service must be Basic tier or higher.");
            }
            if (!configs.Any(c => c.Name == semanticConfigName))
            {
                var prioritizedFields = new SemanticPrioritizedFields
                {
                    TitleField = new SemanticField("HotelName"),
                    ContentFields = { new SemanticField("Description") },
                    KeywordsFields = { new SemanticField("Tags") }
                };
    
                configs.Add(
                    new SemanticConfiguration(
                        semanticConfigName,
                        prioritizedFields
                    )
                );
                Console.WriteLine($"Added new semantic configuration '{semanticConfigName}' to the index definition.");
            }
            else
            {
                Console.WriteLine($"Semantic configuration '{semanticConfigName}' already exists in the index definition.");
            }
            index.SemanticSearch.DefaultConfigurationName = semanticConfigName;
        }
    }
    
  2. Substitua a URL do serviço de pesquisa por um ponto de extremidade válido.

  3. Execute o programa.

  4. A saída é registrada em uma janela de console pelo Console.WriteLine. Você deve ver mensagens para cada etapa, incluindo o JSON do esquema de índice com a nova configuração semântica incluída.

Executar consultas semânticas

Nesta seção, o programa executa várias consultas semânticas em sequência.

  1. Abra o projeto QueryIndex no Visual Studio. O programa consiste no código a seguir.

    Esse código usa um SearchClient para enviar consultas a um índice.

    class SemanticQuery
    {
        static async Task Main(string[] args)
        {
            string searchServiceName = "PUT-YOUR-SEARCH-SERVICE-NAME-HERE";
            string indexName = "hotels-sample-index";
            string endpoint = $"https://{searchServiceName}.search.windows.net";
            var credential = new Azure.Identity.DefaultAzureCredential();
    
            var client = new SearchClient(new Uri(endpoint), indexName, credential);
    
            // Query 1: Simple query
            string searchText = "walking distance to live music";
            Console.WriteLine("\nQuery 1: Simple query using the search string 'walking distance to live music'.");
            await RunQuery(client, searchText, new SearchOptions
            {
                Size = 5,
                QueryType = SearchQueryType.Simple,
                IncludeTotalCount = true,
                Select = { "HotelId", "HotelName", "Description" }
            });
            Console.WriteLine("Press Enter to continue to the next query...");
            Console.ReadLine();
    
            // Query 2: Semantic query (no captions, no answers)
            Console.WriteLine("\nQuery 2: Semantic query (no captions, no answers) for 'walking distance to live music'.");
            var semanticOptions = new SearchOptions
            {
                Size = 5,
                QueryType = SearchQueryType.Semantic,
                SemanticSearch = new SemanticSearchOptions
                {
                    SemanticConfigurationName = "semantic-config"
                },
                IncludeTotalCount = true,
                Select = { "HotelId", "HotelName", "Description" }
            };
            await RunQuery(client, searchText, semanticOptions);
            Console.WriteLine("Press Enter to continue to the next query...");
            Console.ReadLine();
    
            // Query 3: Semantic query with captions
            Console.WriteLine("\nQuery 3: Semantic query with captions.");
            var captionsOptions = new SearchOptions
            {
                Size = 5,
                QueryType = SearchQueryType.Semantic,
                SemanticSearch = new SemanticSearchOptions
                {
                    SemanticConfigurationName = "semantic-config",
                    QueryCaption = new QueryCaption(QueryCaptionType.Extractive)
                    {
                        HighlightEnabled = true
                    }
                },
                IncludeTotalCount = true,
                Select = { "HotelId", "HotelName", "Description" }
            };
            // Add the field(s) you want captions for to the QueryCaption.Fields collection
            captionsOptions.HighlightFields.Add("Description");
            await RunQuery(client, searchText, captionsOptions, showCaptions: true);
            Console.WriteLine("Press Enter to continue to the next query...");
            Console.ReadLine();
    
            // Query 4: Semantic query with answers
            // This query uses different search text designed for an answers scenario
            string searchText2 = "what's a good hotel for people who like to read";
            searchText = searchText2; // Update searchText for the next query
            Console.WriteLine("\nQuery 4: Semantic query with a verbatim answer from the Description field for 'what's a good hotel for people who like to read'.");
            var answersOptions = new SearchOptions
            {
                Size = 5,
                QueryType = SearchQueryType.Semantic,
                SemanticSearch = new SemanticSearchOptions
                {
                    SemanticConfigurationName = "semantic-config",
                    QueryAnswer = new QueryAnswer(QueryAnswerType.Extractive)
                },
                IncludeTotalCount = true,
                Select = { "HotelId", "HotelName", "Description" }
            };
            await RunQuery(client, searchText2, answersOptions, showAnswers: true);
    
            static async Task RunQuery(
            SearchClient client,
            string searchText,
            SearchOptions options,
            bool showCaptions = false,
            bool showAnswers = false)
            {
                try
                {
                    var response = await client.SearchAsync<SearchDocument>(searchText, options);
    
                    if (showAnswers && response.Value.SemanticSearch?.Answers != null)
                    {
                        Console.WriteLine("Extractive Answers:");
                        foreach (var answer in response.Value.SemanticSearch.Answers)
                        {
                            Console.WriteLine($"  {answer.Highlights}");
                        }
                        Console.WriteLine(new string('-', 40));
                    }
    
                    await foreach (var result in response.Value.GetResultsAsync())
                    {
                        var doc = result.Document;
                        // Print captions first if available
                        if (showCaptions && result.SemanticSearch?.Captions != null)
                        {
                            foreach (var caption in result.SemanticSearch.Captions)
                            {
                                Console.WriteLine($"Caption: {caption.Highlights}");
                            }
                        }
                        Console.WriteLine($"HotelId: {doc.GetString("HotelId")}");
                        Console.WriteLine($"HotelName: {doc.GetString("HotelName")}");
                        Console.WriteLine($"Description: {doc.GetString("Description")}");
                        Console.WriteLine($"@search.score: {result.Score}");
    
                        // Print @search.rerankerScore if available
                        if (result.SemanticSearch != null && result.SemanticSearch.RerankerScore.HasValue)
                        {
                            Console.WriteLine($"@search.rerankerScore: {result.SemanticSearch.RerankerScore.Value}");
                        }
                        Console.WriteLine(new string('-', 40));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error querying index: {ex.Message}");
                }
            }
        }
    }
    
  2. Substitua a URL do serviço de pesquisa por um ponto de extremidade válido.

  3. Execute o programa.

  4. A saída é registrada em uma janela de console pelo Console.WriteLine. Você deve ver os resultados da pesquisa para cada consulta.

Saída para consulta semântica (sem legendas ou respostas)

Essa saída é da consulta semântica, sem legendas ou respostas. A cadeia de caracteres de consulta é "a uma distância a pé de música ao vivo".

Aqui, os resultados iniciais da consulta de termo são pontuados novamente usando os modelos de classificação semântica. Para esse conjunto de dados e consulta específicos, os primeiros vários resultados estão em posições semelhantes. Os efeitos da classificação semântica são mais pronunciados no restante dos resultados.

HotelId: 24
HotelName: Uptown Chic Hotel
Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
@search.score: 5.074317
@search.rerankerScore: 2.613231658935547
----------------------------------------
HotelId: 2
HotelName: Old Century Hotel
Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.
@search.score: 5.5153193
@search.rerankerScore: 2.271434783935547
----------------------------------------
HotelId: 4
HotelName: Sublime Palace Hotel
Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.
@search.score: 4.8959594
@search.rerankerScore: 1.9861756563186646
----------------------------------------
HotelId: 39
HotelName: White Mountain Lodge & Suites
Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.
@search.score: 0.7334347
@search.rerankerScore: 1.9615401029586792
----------------------------------------
HotelId: 15
HotelName: By the Market Hotel
Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.
@search.score: 1.5502293
@search.rerankerScore: 1.9085469245910645
----------------------------------------
Press Enter to continue to the next query...

Saída para uma consulta semântica com legendas

Aqui estão os resultados da consulta que adiciona legendas com realce de clique.

Caption: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.
HotelId: 24
HotelName: Uptown Chic Hotel
Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
@search.score: 5.074317
@search.rerankerScore: 2.613231658935547
----------------------------------------
Caption:
HotelId: 2
HotelName: Old Century Hotel
Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.
@search.score: 5.5153193
@search.rerankerScore: 2.271434783935547
----------------------------------------
Caption: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within<em> short walking distance </em>to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort,.
HotelId: 4
HotelName: Sublime Palace Hotel
Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.
@search.score: 4.8959594
@search.rerankerScore: 1.9861756563186646
----------------------------------------
Caption: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend<em> evening entertainment </em>on the patio features special<em> guest musicians </em>or.
HotelId: 39
HotelName: White Mountain Lodge & Suites
Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.
@search.score: 0.7334347
@search.rerankerScore: 1.9615401029586792
----------------------------------------
Caption: Book now and Save up to 30%. Central location. <em>Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood.</em> Brand new rooms. Impeccable service.
HotelId: 15
HotelName: By the Market Hotel
Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.
@search.score: 1.5502293
@search.rerankerScore: 1.9085469245910645
----------------------------------------
Press Enter to continue to the next query...

Saída para respostas semânticas

A consulta final retorna uma resposta semântica. Observe que alteramos a cadeia de caracteres de consulta para este exemplo: "o que é um bom hotel para as pessoas que gostam de ler".

O classificador semântico pode produzir uma resposta para uma cadeia de caracteres de consulta que tem as características de uma pergunta. A resposta gerada é extraída literalmente do seu conteúdo, portanto, não incluirá conteúdo composto como o que você pode esperar de um modelo de conclusão de chat. Se a resposta semântica não for útil para seu cenário, você poderá omitir semantic_answers de seu código.

Para produzir uma resposta semântica, a pergunta e a resposta devem estar alinhadas de perto e o modelo deve encontrar conteúdo que responda claramente à pergunta. Se as respostas potenciais não atenderem a um limite de confiança, o modelo não retornará uma resposta. Para fins de demonstração, a pergunta neste exemplo foi projetada para obter uma resposta para que você possa ver a sintaxe.

Lembre-se de que as respostas são conteúdo verbatim extraído do índice e podem estar faltando frases que um usuário esperaria ver. Para obter respostas compostas geradas por um modelo de conclusão de chat, considere usar um padrão RAG ou recuperação agêntica.

Extractive Answers:
  Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
----------------------------------------
HotelId: 1
HotelName: Stay-Kay City Hotel
Description: This classic hotel is fully-refurbished and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.
@search.score: 2.0361428
@search.rerankerScore: 2.124817371368408
----------------------------------------
HotelId: 16
HotelName: Double Sanctuary Resort
Description: 5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.
@search.score: 3.759768
@search.rerankerScore: 2.0705394744873047
----------------------------------------
HotelId: 38
HotelName: Lakeside B & B
Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
@search.score: 0.7308748
@search.rerankerScore: 2.041472911834717
----------------------------------------
HotelId: 2
HotelName: Old Century Hotel
Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.
@search.score: 3.391012
@search.rerankerScore: 2.0231292247772217
----------------------------------------
HotelId: 15
HotelName: By the Market Hotel
Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.
@search.score: 1.3198771
@search.rerankerScore: 2.021622657775879
----------------------------------------

Neste início rápido, você aprenderá a usar a classificação semântica adicionando uma configuração semântica a um índice de pesquisa e adicionando parâmetros semânticos a uma consulta. Você pode usar o índice de exemplo de hotéis (hotels-sample-index) ou um dos seus.

No Azure AI Search, a classificação semântica é a funcionalidade do lado da consulta que usa a compreensão de leitura de computador da Microsoft para pontuar os resultados da pesquisa, promovendo as correspondências mais semanticamente relevantes para o topo da lista. Dependendo do conteúdo e da consulta, a classificação semântica pode melhorar significativamente a relevância da pesquisa com o mínimo de esforço do desenvolvedor.

Você pode adicionar uma configuração semântica a um índice existente sem nenhum requisito de recompilação. A classificação semântica é mais eficaz em texto informativo ou descritivo.

Pré-requisitos

Configurar o acesso

É possível se conectar ao serviço Pesquisa de IA do Azure usando as chaves de API ou o Microsoft Entra ID com atribuições de função. É mais fácil usar as chaves para começar, mas as funções são mais seguras. Para obter mais informações, confira Conectar-se à Pesquisa de IA do Azure usando funções.

Para configurar o acesso baseado em função:

  1. Entre no portal do Azure e selecione seu serviço de pesquisa.

  2. No painel à esquerda, selecione Configurações>Chaves.

  3. No Controle de Acesso à API, selecione Controle de Acesso Baseado em Função ou Ambos se precisar de tempo para fazer a transição de clientes para acesso baseado em função.

  4. No painel esquerdo, selecione Controle de acesso (IAM).

  5. Selecione Adicionar>Adicionar atribuição de função.

  6. Atribua as funções de Colaborador do Serviço de Pesquisa e Colaborador de Dados do Índice de Pesquisa à sua conta de usuário.

Começar com um índice

Este início rápido pressupõe um índice existente e o modifica para incluir uma configuração semântica. Recomendamos o índice de exemplo de hotéis que você pode criar em minutos usando um assistente do portal do Azure.

Para começar com um índice existente:

  1. Entre no portal do Azure e localize seu serviço de pesquisa.

  2. EmGerenciamento de Pesquisa>Índices, selecione o hotéis-sample-index.

  3. Selecione configurações semânticas para garantir que o índice não tenha uma configuração semântica.

    Captura de tela de uma página de configuração semântica vazia no portal do Azure.

  4. Selecione o Gerenciador de Pesquisa e, em seguida, selecione o modo de exibição JSON.

  5. Cole os dados JSON abaixo no editor de consultas.

    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true
    }
    

    Captura de tela de uma consulta no Gerenciador de Pesquisa no portal.

  6. Selecione Pesquisar para executar a consulta.

    Essa consulta é uma pesquisa de palavra-chave. A resposta deve ser semelhante ao exemplo a seguir, conforme pontuação pelo classificador BM25 L1 padrão para pesquisa de texto completo.

    Para garantir a legibilidade, o exemplo seleciona apenas os campos HotelId, HotelName, e Description. Os resultados contêm correspondências verbais nos termos da consulta (walking, , distance, live) musicou variantes linguísticas (walk, living).

    "@odata.count": 13,
    "value": [
      {
        "@search.score": 5.5153193,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
      },
      {
        "@search.score": 5.074317,
        "HotelId": "24",
        "HotelName": "Uptown Chic Hotel",
        "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
      },
      {
        "@search.score": 4.8959594,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
      },
      {
        "@search.score": 2.5966604,
        "HotelId": "35",
        "HotelName": "Bellevue Suites",
        "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport."
      },
      {
        "@search.score": 2.566386,
        "HotelId": "47",
        "HotelName": "Country Comfort Inn",
        "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome."
      },
      {
        "@search.score": 2.2405157,
        "HotelId": "9",
        "HotelName": "Smile Up Hotel",
        "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene."
      },
      {
        "@search.score": 2.1737604,
        "HotelId": "8",
        "HotelName": "Foot Happy Suites",
        "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further."
      },
      {
        "@search.score": 2.0364518,
        "HotelId": "31",
        "HotelName": "Country Residence Hotel",
        "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
      },
      {
        "@search.score": 1.7595702,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
      },
      {
        "@search.score": 1.5502293,
        "HotelId": "15",
        "HotelName": "By the Market Hotel",
        "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
      },
      {
        "@search.score": 1.3302404,
        "HotelId": "42",
        "HotelName": "Rock Bottom Resort & Campground",
        "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away."
      },
      {
        "@search.score": 0.9050383,
        "HotelId": "38",
        "HotelName": "Lakeside B & B",
        "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
      },
      {
        "@search.score": 0.7334347,
        "HotelId": "39",
        "HotelName": "White Mountain Lodge & Suites",
        "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
      }
    ]
    

Esta consulta mostra a aparência da resposta antes da classificação semântica ser aplicada. Posteriormente, você pode executar a mesma consulta depois que a classificação semântica é configurada para ver como a resposta muda.

Dica

Você pode adicionar uma configuração semântica no portal do Azure. No entanto, se você quiser aprender a adicionar uma configuração semântica programaticamente, continue com este início rápido.

Configurar o cliente

Neste início rápido, você usará um IDE e a biblioteca de clientes @azure/search-documents para adicionar classificação semântica a um índice de pesquisa existente.

O início rápido pressupõe que o seguinte está disponível em seu computador:

Dica

É possível baixar o código-fonte para começar com um projeto concluído, ou seguir as etapas neste artigo para criar o seu.

Configurar o ambiente de desenvolvimento local

  1. Inicie o Visual Studio Code em um novo diretório.

    mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart
    code .
    
  2. Crie um novo pacote para módulos de ESM no diretório do projeto.

    npm init -y
    npm pkg set type=module
    
  3. Instale pacotes, incluindo azure-search-documents.

    npm install @azure/identity @azure/search-documents dotenv
    
  4. Crie .env e forneça o ponto de extremidade do serviço de pesquisa. Você pode obter o endpoint no portal do Azure na página Visão geral do serviço de pesquisa.

    AZURE_SEARCH_ENDPOINT=YOUR-SEARCH-SERVICE-ENDPOINT
    AZURE_SEARCH_INDEX_NAME=hotels-sample-index
    SEMANTIC_CONFIGURATION_NAME=semantic-config
    
  5. Crie um diretório src no diretório do projeto.

    mkdir src
    

Entrar no Azure

Se você entrou no portal do Azure, está conectado ao Azure. Se você não tiver certeza, use a CLI do Azure ou o Azure PowerShell para fazer logon: az login ou az connect. Se você tiver vários locatários e assinaturas, consulte Início Rápido: Conectar sem chaves para obter ajuda sobre como se conectar.

Criar um arquivo de autenticação comum

Crie um arquivo em ./src chamado config.ts para fazer a leitura do arquivo .env e manter as variáveis de ambiente e a credencial de autenticação. Copie no código a seguir; não altere-o. Esse arquivo será usado por todos os outros arquivos neste início rápido.

import { DefaultAzureCredential } from "@azure/identity";

// Configuration - use environment variables
export const searchEndpoint = process.env.AZURE_SEARCH_ENDPOINT || "PUT-YOUR-SEARCH-SERVICE-ENDPOINT-HERE";
export const indexName = process.env.AZURE_SEARCH_INDEX_NAME || "hotels-sample-index";
export const semanticConfigurationName = process.env.SEMANTIC_CONFIGURATION_NAME || "semantic-config";

// Create credential
export const credential = new DefaultAzureCredential();

console.log(`Using Azure Search endpoint: ${searchEndpoint}`);
console.log(`Using index name: ${indexName}\n\n`);

Obter o esquema de índice

Nesta seção, você obterá as configurações para o índice hotels-sample-index existente em seu serviço de pesquisa.

  1. Crie um arquivo em ./src chamado getIndexSettings.js e copie o código a seguir.

    import {
        SearchIndexClient
    } from "@azure/search-documents";
    import { searchEndpoint, indexName, credential } from "./config.js";
    
    const indexClient = new SearchIndexClient(searchEndpoint, credential);
    
    console.log('Getting semantic search index settings...');
    
    // Get the existing schema
    const index = await indexClient.getIndex(indexName);
    
    console.log(`Index name: ${index.name}`);
    console.log(`Number of fields: ${index.fields.length}`);
    
    for(const field of index.fields) {
        console.log(`Field: ${field.name}, Type: ${field.type}, Searchable: ${field.searchable}`);
    }
    
    if(index.semanticSearch && index.semanticSearch.configurations) {
        console.log(`Semantic search configurations: ${index.semanticSearch.configurations.length}`);
        for(const config of index.semanticSearch.configurations) {
            console.log(`Configuration name: ${config.name}`);
            console.log(`Title field: ${config.prioritizedFields.titleField?.name}`);
        }
    } else {
        console.log("No semantic configuration exists for this index.");
    }
    
  2. Execute o código.

    node -r dotenv/config src/getIndexSettings.js
    
  3. A saída é o nome do índice, da lista de campos e de uma instrução que indica se existe uma configuração semântica. Para os propósitos deste início rápido, a mensagem deve dizer No semantic configuration exists for this index.

Atualizar o índice com uma configuração semântica

  1. Crie um arquivo em ./src chamado updateIndexSettings.js e copie o código a seguir para adicionar uma configuração semântica ao índice hotels-sample-index existente em seu serviço de pesquisa. Nenhum documento de pesquisa é excluído por essa operação e seu índice ainda está operacional depois que a configuração é adicionada.

    import {
        SearchIndexClient
    } from "@azure/search-documents";
    import { searchEndpoint, indexName, credential, semanticConfigurationName } from "./config.js";
    
    try {
    
        const indexClient = new SearchIndexClient(searchEndpoint, credential);
    
        const existingIndex = await indexClient.getIndex(indexName);
    
        const fields = {
            titleField: {
                name: "HotelName"
            },
            keywordsFields: [{
                name: "Tags"
            }],
            contentFields: [{
                name: "Description"
            }]
        };
    
        const newSemanticConfiguration = {
            name: semanticConfigurationName,
            prioritizedFields: fields
        };
    
        // Add the new semantic configuration to the existing index
        if (existingIndex.semanticSearch && existingIndex.semanticSearch.configurations) {
            existingIndex.semanticSearch.configurations.push(newSemanticConfiguration);
        } else {
            const configExists = existingIndex.semanticSearch?.configurations?.some(
                config => config.name === semanticConfigurationName
            );
            if (!configExists) {
                existingIndex.semanticSearch = {
                    configurations: [newSemanticConfiguration]
                };
            }
        }
    
        await indexClient.createOrUpdateIndex(existingIndex);
    
        const updatedIndex = await indexClient.getIndex(indexName);
    
        console.log(`Semantic configurations:`);
        console.log("-".repeat(40));
    
        if (updatedIndex.semanticSearch && updatedIndex.semanticSearch.configurations) {
            for (const config of updatedIndex.semanticSearch.configurations) {
                console.log(`Configuration name: ${config.name}`);
                console.log(`Title field: ${config.prioritizedFields.titleField?.name}`);
                console.log(`Keywords fields: ${config.prioritizedFields.keywordsFields?.map(f => f.name).join(", ")}`);
                console.log(`Content fields: ${config.prioritizedFields.contentFields?.map(f => f.name).join(", ")}`);
                console.log("-".repeat(40));
            }
        } else {
            console.log("No semantic configurations found.");
        }
    
        console.log("Semantic configuration updated successfully.");
    } catch (error) {
        console.error("Error updating semantic configuration:", error);
    }
    
  2. Execute o código.

    node -r dotenv/config src/updateIndexSettings.js
    
  3. A saída é a configuração semântica que você acabou de adicionar. Semantic configuration updated successfully.

Executar consultas semânticas

Depois que o índice hotels-sample-index tiver uma configuração semântica, você poderá executar consultas que incluem parâmetros semânticos.

  1. Crie um arquivo em ./src chamado semanticQuery.js e copie o código a seguir para criar uma consulta semântica do índice. Esse é o requisito mínimo para invocar a classificação semântica.

    import { SearchClient } from "@azure/search-documents";
    import { credential, searchEndpoint, indexName, semanticConfigurationName } from "./config.js";
    
    const searchClient = new SearchClient(
        searchEndpoint,
        indexName,
        credential
    );
    
    const results = await searchClient.search("walking distance to live music", {
        queryType: "semantic",
        semanticSearchOptions: {
            configurationName: semanticConfigurationName
        },
        select: ["HotelId", "HotelName", "Description"]
    });
    
    let rowNumber = 1;
    for await (const result of results.results) {
        // Log each result
        const doc = result.document;
        const score = result.score;
        const rerankerScoreDisplay = result.rerankerScore;
    
        console.log(`Search result #${rowNumber++}:`);
        console.log(`  Re-ranker Score: ${rerankerScoreDisplay}`);
        console.log(`  HotelId: ${doc.HotelId}`);
        console.log(`  HotelName: ${doc.HotelName}`);
        console.log(`  Description: ${doc.Description || 'N/A'}\n`);
    }
    
  2. Execute o código.

    node -r dotenv/config src/semanticQuery.js
    
  3. A saída deve consistir em 13 documentos, ordenados por rerankerScoreDisplay.

Legendas de retorno

Opcionalmente, você pode adicionar legendas para extrair partes do texto e aplicar o realce de clique aos termos e frases importantes. Essa consulta adiciona legendas.

  1. Crie um arquivo em ./src chamado semanticQueryReturnCaptions.js e copie o código a seguir para adicionar legendas à consulta.

    import { SearchClient } from "@azure/search-documents";
    import { credential, searchEndpoint, indexName, semanticConfigurationName } from "./config.js";
    
    const searchClient = new SearchClient(
        searchEndpoint,
        indexName,
        credential
    );
    
    console.log(`Using semantic configuration: ${semanticConfigurationName}`);
    console.log("Search query: walking distance to live music");
    
    const results = await searchClient.search("walking distance to live music", {
        queryType: "semantic",
        semanticSearchOptions: {
            configurationName: semanticConfigurationName,
            captions: {
                captionType: "extractive",
                highlight: true
            }
        },
        select: ["HotelId", "HotelName", "Description"],
    });
    
    console.log(`Found ${results.count} results with semantic search\n`);
    let rowNumber = 1;
    
    for await (const result of results.results) {
        // Log each result
        const doc = result.document;
        const rerankerScoreDisplay = result.rerankerScore;
    
        console.log(`Search result #${rowNumber++}:`);
        console.log(`  Re-ranker Score: ${rerankerScoreDisplay}`);
        console.log(`  HotelName: ${doc.HotelName}`);
        console.log(`  Description: ${doc.Description || 'N/A'}\n`);
    
        // Caption handling with better debugging
        const captions = result.captions;
    
        if (captions && captions.length > 0) {
            const caption = captions[0];
    
            if (caption.highlights) {
                console.log(`  Caption with highlights: ${caption.highlights}`);
            } else if (caption.text) {
                console.log(`  Caption text: ${caption.text}`);
            } else {
                console.log(`  Caption exists but has no text or highlights content`);
            }
        } else {
            console.log("  No captions found for this result");
        }
        console.log("-".repeat(60));
    }
    
  2. Execute o código.

    node -r dotenv/config src/semanticQueryReturnCaptions.js
    
  3. A saída deve incluir um novo elemento de legenda ao lado do campo de pesquisa. Legendas são as passagens mais relevantes em um resultado. Se o índice incluir partes maiores de texto, uma legenda será útil para extrair as frases mais interessantes.

    Search result #1:
      Re-ranker Score: 2.613231658935547
      HotelName: Uptown Chic Hotel
      Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
    
      Caption with highlights: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.
    

Retornar respostas semânticas

Nesta consulta final, retorne respostas semânticas.

O classificador semântico pode produzir uma resposta para uma cadeia de caracteres de consulta que tem as características de uma pergunta. A resposta gerada é extraída literalmente do seu conteúdo, portanto, não incluirá conteúdo composto como o que você pode esperar de um modelo de conclusão de chat. Se a resposta semântica não for útil para seu cenário, você poderá omitir semantic_answers de seu código.

Para produzir uma resposta semântica, a pergunta e a resposta devem estar alinhadas de perto e o modelo deve encontrar conteúdo que responda claramente à pergunta. Se as respostas potenciais não atenderem a um limite de confiança, o modelo não retornará uma resposta. Para fins de demonstração, a pergunta neste exemplo foi projetada para obter uma resposta para que você possa ver a sintaxe.

  1. Crie um arquivo em ./src chamadosemanticAnswer.js e copie o código a seguir para obter respostas semânticas.

    import { SearchClient } from "@azure/search-documents";
    import { credential, searchEndpoint, indexName, semanticConfigurationName } from "./config.js";
    
    const searchClient = new SearchClient(
        searchEndpoint,
        indexName,
        credential
    );
    
    const results = await searchClient.search("What's a good hotel for people who like to read", {
        queryType: "semantic",
        semanticSearchOptions: {
            configurationName: semanticConfigurationName,
            captions: {
                captionType: "extractive"
            },
            answers: {
                answerType: "extractive"
            }
        },
        select: ["HotelName", "Description", "Category"]
    });
    
    console.log(`Answers:\n\n`);
    let rowNumber = 1; 
    
    // Extract semantic answers from the search results
    const semanticAnswers = results.answers;
    for (const answer of semanticAnswers || []) {
        console.log(`Semantic answer result #${rowNumber++}:`);
        if (answer.highlights) {
            console.log(`Semantic Answer: ${answer.highlights}`);
        } else {
            console.log(`Semantic Answer: ${answer.text}`);
        }
        console.log(`Semantic Answer Score: ${answer.score}\n\n`);
    }
    
    console.log(`Search Results:\n\n`);
    rowNumber = 1;
    
    // Iterate through the search results
    for await (const result of results.results) {
        // Log each result
        const doc = result.document;
        const rerankerScoreDisplay = result.rerankerScore;
    
        console.log(`Search result #${rowNumber++}:`);
        console.log(`${rerankerScoreDisplay}`);
        console.log(`${doc.HotelName}`);
        console.log(`${doc.Description || 'N/A'}`);
    
        const captions = result.captions;
    
        if (captions && captions.length > 0) {
            const caption = captions[0];
            if (caption.highlights) {
                console.log(`Caption: ${caption.highlights}\n`);
            } else {
                console.log(`Caption: ${caption.text}\n`);
            }
        }
    }
    
  2. Execute o código.

    node -r dotenv/config src/semanticAnswer.js
    
  3. A saída deve ser semelhante ao exemplo a seguir, em que a melhor resposta à pergunta é extraída de um dos resultados.

    Lembre-se de que as respostas são conteúdo verbatim extraído do índice e podem estar faltando frases que um usuário esperaria ver. Para obter respostas compostas geradas por um modelo de conclusão de chat, considere usar um padrão RAG ou recuperação agêntica.

    Semantic answer result #1:
    Semantic Answer: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
    Semantic Answer Score: 0.9829999804496765
    

Neste início rápido, você aprenderá a usar a classificação semântica adicionando uma configuração semântica a um índice de pesquisa e adicionando parâmetros semânticos a uma consulta. Você pode usar o índice de exemplo de hotéis (hotels-sample-index) ou um dos seus.

No Azure AI Search, a classificação semântica é a funcionalidade do lado da consulta que usa a compreensão de leitura de computador da Microsoft para pontuar os resultados da pesquisa, promovendo as correspondências mais semanticamente relevantes para o topo da lista. Dependendo do conteúdo e da consulta, a classificação semântica pode melhorar significativamente a relevância da pesquisa com o mínimo de esforço do desenvolvedor.

Você pode adicionar uma configuração semântica a um índice existente sem nenhum requisito de recompilação. A classificação semântica é mais eficaz em texto informativo ou descritivo.

Pré-requisitos

Configurar o acesso

É possível se conectar ao serviço Pesquisa de IA do Azure usando as chaves de API ou o Microsoft Entra ID com atribuições de função. É mais fácil usar as chaves para começar, mas as funções são mais seguras. Para obter mais informações, confira Conectar-se à Pesquisa de IA do Azure usando funções.

Para configurar o acesso baseado em função:

  1. Entre no portal do Azure e selecione seu serviço de pesquisa.

  2. No painel à esquerda, selecione Configurações>Chaves.

  3. No Controle de Acesso à API, selecione Controle de Acesso Baseado em Função ou Ambos se precisar de tempo para fazer a transição de clientes para acesso baseado em função.

  4. No painel esquerdo, selecione Controle de acesso (IAM).

  5. Selecione Adicionar>Adicionar atribuição de função.

  6. Atribua as funções de Colaborador do Serviço de Pesquisa e Colaborador de Dados do Índice de Pesquisa à sua conta de usuário.

Começar com um índice

Este início rápido pressupõe um índice existente e o modifica para incluir uma configuração semântica. Recomendamos o índice de exemplo de hotéis que você pode criar em minutos usando um assistente do portal do Azure.

Para começar com um índice existente:

  1. Entre no portal do Azure e localize seu serviço de pesquisa.

  2. EmGerenciamento de Pesquisa>Índices, selecione o hotéis-sample-index.

  3. Selecione configurações semânticas para garantir que o índice não tenha uma configuração semântica.

    Captura de tela de uma página de configuração semântica vazia no portal do Azure.

  4. Selecione o Gerenciador de Pesquisa e, em seguida, selecione o modo de exibição JSON.

  5. Cole os dados JSON abaixo no editor de consultas.

    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true
    }
    

    Captura de tela de uma consulta no Gerenciador de Pesquisa no portal.

  6. Selecione Pesquisar para executar a consulta.

    Essa consulta é uma pesquisa de palavra-chave. A resposta deve ser semelhante ao exemplo a seguir, conforme pontuação pelo classificador BM25 L1 padrão para pesquisa de texto completo.

    Para garantir a legibilidade, o exemplo seleciona apenas os campos HotelId, HotelName, e Description. Os resultados contêm correspondências verbais nos termos da consulta (walking, , distance, live) musicou variantes linguísticas (walk, living).

    "@odata.count": 13,
    "value": [
      {
        "@search.score": 5.5153193,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
      },
      {
        "@search.score": 5.074317,
        "HotelId": "24",
        "HotelName": "Uptown Chic Hotel",
        "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
      },
      {
        "@search.score": 4.8959594,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
      },
      {
        "@search.score": 2.5966604,
        "HotelId": "35",
        "HotelName": "Bellevue Suites",
        "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport."
      },
      {
        "@search.score": 2.566386,
        "HotelId": "47",
        "HotelName": "Country Comfort Inn",
        "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome."
      },
      {
        "@search.score": 2.2405157,
        "HotelId": "9",
        "HotelName": "Smile Up Hotel",
        "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene."
      },
      {
        "@search.score": 2.1737604,
        "HotelId": "8",
        "HotelName": "Foot Happy Suites",
        "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further."
      },
      {
        "@search.score": 2.0364518,
        "HotelId": "31",
        "HotelName": "Country Residence Hotel",
        "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
      },
      {
        "@search.score": 1.7595702,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
      },
      {
        "@search.score": 1.5502293,
        "HotelId": "15",
        "HotelName": "By the Market Hotel",
        "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
      },
      {
        "@search.score": 1.3302404,
        "HotelId": "42",
        "HotelName": "Rock Bottom Resort & Campground",
        "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away."
      },
      {
        "@search.score": 0.9050383,
        "HotelId": "38",
        "HotelName": "Lakeside B & B",
        "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
      },
      {
        "@search.score": 0.7334347,
        "HotelId": "39",
        "HotelName": "White Mountain Lodge & Suites",
        "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
      }
    ]
    

Esta consulta mostra a aparência da resposta antes da classificação semântica ser aplicada. Posteriormente, você pode executar a mesma consulta depois que a classificação semântica é configurada para ver como a resposta muda.

Dica

Você pode adicionar uma configuração semântica no portal do Azure. No entanto, se você quiser aprender a adicionar uma configuração semântica programaticamente, continue com este início rápido.

Configurar o cliente

Neste início rápido, você usará um IDE e a biblioteca de clientes do SDK java do Azure AI Search para adicionar classificação semântica a um índice de pesquisa existente.

O início rápido pressupõe que o seguinte está disponível em seu computador:

Configurar o ambiente de desenvolvimento local

  1. Crie um novo diretório de projeto do Maven.

    mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart
    code .
    
  2. Crie um arquivo pom.xml com as dependências necessárias.

    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
             http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.azure.search</groupId>
        <artifactId>semantic-ranking-quickstart</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>21</maven.compiler.source>
            <maven.compiler.target>21</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>com.azure</groupId>
                <artifactId>azure-search-documents</artifactId>
                <version>11.7.8</version>
            </dependency>
            <dependency>
                <groupId>com.azure</groupId>
                <artifactId>azure-identity</artifactId>
                <version>1.17.0</version>
            </dependency>
        </dependencies>
    </project>
    
  3. Compile o projeto para resolver as dependências.

    mvn compile
    
  4. Crie a estrutura do diretório de origem.

    mkdir -p src/main/java/com/azure/search/quickstart
    mkdir -p src/main/resources
    
  5. Crie um arquivo no diretório application.properties e forneça o ponto de extremidade do serviço de pesquisa src/main/resources. Você pode obter o endpoint no portal do Azure na página Visão geral do serviço de pesquisa.

    azure.search.endpoint=YOUR-SEARCH-SERVICE-ENDPOINT
    azure.search.index.name=hotels-sample-index
    semantic.configuration.name=semantic-config
    

Entrar no Azure

Se você entrou no portal do Azure, está conectado ao Azure. Se você não tiver certeza, use a CLI do Azure para fazer logon: az login. Se você tiver vários locatários e assinaturas, consulte Início Rápido: Conectar sem chaves para obter ajuda sobre como se conectar.

Criar uma classe de configuração comum

Crie um SearchConfig.java arquivo no src/main/java/com/azure/search/quickstart diretório para ler o arquivo de propriedades e manter os valores de configuração e a credencial de autenticação.

package com.azure.search.quickstart;

import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SearchConfig {
    private static final Properties properties = new Properties();

    static {
        try (InputStream input = SearchConfig.class.getClassLoader()
            .getResourceAsStream("application.properties")) {
            properties.load(input);
        } catch (IOException e) {
            throw new RuntimeException(
                "Failed to load application.properties", e);
        }
    }

    public static final String SEARCH_ENDPOINT =
        properties.getProperty("azure.search.endpoint");
    public static final String INDEX_NAME =
        properties.getProperty("azure.search.index.name");
    public static final String SEMANTIC_CONFIG_NAME =
        properties.getProperty("semantic.configuration.name");

    public static final DefaultAzureCredential CREDENTIAL =
        new DefaultAzureCredentialBuilder().build();

    static {
        System.out.println("Using Azure Search endpoint: " + SEARCH_ENDPOINT);
        System.out.println("Using index name: " + INDEX_NAME + "\n");
    }
}

Obter o esquema de índice

Nesta seção, você obterá as configurações para o índice hotels-sample-index existente em seu serviço de pesquisa.

  1. Crie um GetIndexSettings.java arquivo no src/main/java/com/azure/search/quickstart diretório.

    package com.azure.search.quickstart;
    
    import com.azure.search.documents.indexes.SearchIndexClientBuilder;
    import com.azure.search.documents.indexes.models.SearchField;
    import com.azure.search.documents.indexes.models.SearchIndex;
    import com.azure.search.documents.indexes.models.SemanticConfiguration;
    import com.azure.search.documents.indexes.models.SemanticField;
    import com.azure.search.documents.indexes.models.SemanticSearch;
    
    public class GetIndexSettings {
        public static void main(String[] args) {
            var indexClient = new SearchIndexClientBuilder()
                .endpoint(SearchConfig.SEARCH_ENDPOINT)
                .credential(SearchConfig.CREDENTIAL)
                .buildClient();
    
            System.out.println("Getting semantic search index settings...");
    
            SearchIndex index = indexClient.getIndex(SearchConfig.INDEX_NAME);
    
            System.out.println("Index name: " + index.getName());
            System.out.println("Number of fields: " + index.getFields().size());
    
            for (SearchField field : index.getFields()) {
                System.out.printf("Field: %s, Type: %s, Searchable: %s%n",
                    field.getName(), field.getType(), field.isSearchable());
            }
    
            SemanticSearch semanticSearch = index.getSemanticSearch();
            if (semanticSearch != null &&
                semanticSearch.getConfigurations() != null) {
                System.out.println("Semantic search configurations: " +
                    semanticSearch.getConfigurations().size());
                for (SemanticConfiguration config :
                    semanticSearch.getConfigurations()) {
                    System.out.println("Configuration name: " + config.getName());
                    SemanticField titleField = config.getPrioritizedFields().getTitleField();
                    if (titleField != null) {
                        System.out.println("Title field: " +
                            titleField.getFieldName());
                    }
                }
            } else {
                System.out.println(
                    "No semantic configuration exists for this index.");
            }
    
            System.exit(0);
        }
    }
    
  2. Compile e execute o código.

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.GetIndexSettings"
    
  3. A saída é o nome do índice, da lista de campos e de uma instrução que indica se existe uma configuração semântica. Para os propósitos deste início rápido, a mensagem deve dizer No semantic configuration exists for this index.

Atualizar o índice com uma configuração semântica

  1. Crie um UpdateIndexSettings.java arquivo no src/main/java/com/azure/search/quickstart diretório para adicionar uma configuração semântica ao índice existente hotels-sample-index em seu serviço de pesquisa.

    package com.azure.search.quickstart;
    
    import com.azure.search.documents.indexes.SearchIndexClientBuilder;
    import com.azure.search.documents.indexes.models.SearchIndex;
    import com.azure.search.documents.indexes.models.SemanticConfiguration;
    import com.azure.search.documents.indexes.models.SemanticField;
    import com.azure.search.documents.indexes.models.SemanticPrioritizedFields;
    import com.azure.search.documents.indexes.models.SemanticSearch;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class UpdateIndexSettings {
        public static void main(String[] args) {
            try {
                var indexClient = new SearchIndexClientBuilder()
                    .endpoint(SearchConfig.SEARCH_ENDPOINT)
                    .credential(SearchConfig.CREDENTIAL)
                    .buildClient();
    
                SearchIndex existingIndex =
                    indexClient.getIndex(SearchConfig.INDEX_NAME);
    
                // Create prioritized fields for semantic configuration
                var prioritizedFields = new SemanticPrioritizedFields()
                    .setTitleField(new SemanticField("HotelName"))
                    .setKeywordsFields(List.of(new SemanticField("Tags")))
                    .setContentFields(List.of(new SemanticField("Description")));
    
                var newSemanticConfiguration = new SemanticConfiguration(
                    SearchConfig.SEMANTIC_CONFIG_NAME, prioritizedFields);
    
                // Add the semantic configuration to the index
                SemanticSearch semanticSearch = existingIndex.getSemanticSearch();
                if (semanticSearch == null) {
                    semanticSearch = new SemanticSearch();
                    existingIndex.setSemanticSearch(semanticSearch);
                }
    
                List<SemanticConfiguration> configurations =
                    semanticSearch.getConfigurations();
                if (configurations == null) {
                    configurations = new ArrayList<>();
                    semanticSearch.setConfigurations(configurations);
                }
    
                // Check if configuration already exists
                boolean configExists = configurations.stream()
                    .anyMatch(config -> SearchConfig.SEMANTIC_CONFIG_NAME
                        .equals(config.getName()));
    
                if (!configExists) {
                    configurations.add(newSemanticConfiguration);
                }
    
                indexClient.createOrUpdateIndex(existingIndex);
    
                SearchIndex updatedIndex =
                    indexClient.getIndex(SearchConfig.INDEX_NAME);
    
                System.out.println("Semantic configurations:");
                System.out.println("-".repeat(40));
    
                SemanticSearch updatedSemanticSearch =
                    updatedIndex.getSemanticSearch();
                if (updatedSemanticSearch != null &&
                    updatedSemanticSearch.getConfigurations() != null) {
                    for (SemanticConfiguration config :
                        updatedSemanticSearch.getConfigurations()) {
                        System.out.println("Configuration name: " + config.getName());
    
                        SemanticPrioritizedFields fields =
                            config.getPrioritizedFields();
                        if (fields.getTitleField() != null) {
                            System.out.println("Title field: " +
                                fields.getTitleField().getFieldName());
                        }
                        if (fields.getKeywordsFields() != null) {
                            List<String> keywords = fields.getKeywordsFields().stream()
                                .map(SemanticField::getFieldName)
                                .toList();
                            System.out.println("Keywords fields: " +
                                String.join(", ", keywords));
                        }
                        if (fields.getContentFields() != null) {
                            List<String> content = fields.getContentFields().stream()
                                .map(SemanticField::getFieldName)
                                .toList();
                            System.out.println("Content fields: " +
                                String.join(", ", content));
                        }
                        System.out.println("-".repeat(40));
                    }
                } else {
                    System.out.println("No semantic configurations found.");
                }
    
                System.out.println("Semantic configuration updated successfully.");
    
                System.exit(0);
            } catch (Exception e) {
                System.err.println("Error updating semantic configuration: " +
                    e.getMessage());
            }
        }
    }
    
  2. Compile e execute o código.

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.UpdateIndexSettings"
    
  3. A saída é a configuração semântica que você acabou de adicionar. Semantic configuration updated successfully.

Executar consultas semânticas

Depois que o hotels-sample-index índice tiver uma configuração semântica, você poderá executar consultas que incluem parâmetros semânticos.

  1. Crie um SemanticQuery.java arquivo no src/main/java/com/azure/search/quickstart diretório para criar uma consulta semântica do índice.

    package com.azure.search.quickstart;
    
    import com.azure.search.documents.SearchClientBuilder;
    import com.azure.search.documents.SearchDocument;
    import com.azure.search.documents.models.QueryType;
    import com.azure.search.documents.models.SearchOptions;
    import com.azure.search.documents.models.SearchResult;
    import com.azure.search.documents.models.SemanticSearchOptions;
    import com.azure.search.documents.util.SearchPagedIterable;
    
    public class SemanticQuery {
        public static void main(String[] args) {
            var searchClient = new SearchClientBuilder()
                .endpoint(SearchConfig.SEARCH_ENDPOINT)
                .indexName(SearchConfig.INDEX_NAME)
                .credential(SearchConfig.CREDENTIAL)
                .buildClient();
    
            var searchOptions = new SearchOptions()
                .setQueryType(QueryType.SEMANTIC)
                .setSemanticSearchOptions(new SemanticSearchOptions()
                    .setSemanticConfigurationName(SearchConfig.SEMANTIC_CONFIG_NAME))
                .setSelect("HotelId", "HotelName", "Description");
    
            SearchPagedIterable results = searchClient.search(
                "walking distance to live music", searchOptions, null);
    
            int rowNumber = 1;
            for (SearchResult result : results) {
                var document = result.getDocument(SearchDocument.class);
                double rerankerScore = result.getSemanticSearch().getRerankerScore();
    
                System.out.printf("Search result #%d:%n", rowNumber++);
                System.out.printf("  Re-ranker Score: %.2f%n", rerankerScore);
                System.out.printf("  HotelId: %s%n", document.get("HotelId"));
                System.out.printf("  HotelName: %s%n", document.get("HotelName"));
                System.out.printf("  Description: %s%n%n",
                    document.get("Description") != null ?
                        document.get("Description") : "N/A");
            }
    
            System.exit(0);
        }
    }
    
  2. Compile e execute o código.

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticQuery"
    
  3. A saída deve consistir em 13 documentos, ordenados pela pontuação do reclassificador.

Legendas de retorno

Opcionalmente, você pode adicionar legendas para extrair partes do texto e aplicar o realce de clique aos termos e frases importantes.

  1. Crie um SemanticQueryWithCaptions.java arquivo no src/main/java/com/azure/search/quickstart diretório.

    package com.azure.search.quickstart;
    
    import com.azure.search.documents.SearchClientBuilder;
    import com.azure.search.documents.SearchDocument;
    import com.azure.search.documents.models.QueryCaption;
    import com.azure.search.documents.models.QueryCaptionResult;
    import com.azure.search.documents.models.QueryCaptionType;
    import com.azure.search.documents.models.QueryType;
    import com.azure.search.documents.models.SearchOptions;
    import com.azure.search.documents.models.SearchResult;
    import com.azure.search.documents.models.SemanticSearchOptions;
    import com.azure.search.documents.util.SearchPagedIterable;
    import java.util.List;
    
    public class SemanticQueryWithCaptions {
        public static void main(String[] args) {
            var searchClient = new SearchClientBuilder()
                .endpoint(SearchConfig.SEARCH_ENDPOINT)
                .indexName(SearchConfig.INDEX_NAME)
                .credential(SearchConfig.CREDENTIAL)
                .buildClient();
    
            System.out.println("Using semantic configuration: " +
                SearchConfig.SEMANTIC_CONFIG_NAME);
            System.out.println("Search query: walking distance to live music");
    
            var searchOptions = new SearchOptions()
                .setQueryType(QueryType.SEMANTIC)
                .setSemanticSearchOptions(new SemanticSearchOptions()
                    .setSemanticConfigurationName(SearchConfig.SEMANTIC_CONFIG_NAME)
                    .setQueryCaption(new QueryCaption(QueryCaptionType.EXTRACTIVE)
                        .setHighlightEnabled(true)))
                .setSelect("HotelId", "HotelName", "Description");
    
            SearchPagedIterable results = searchClient.search(
                "walking distance to live music", searchOptions, null);
    
            System.out.printf("Found results with semantic search%n%n");
            int rowNumber = 1;
    
            for (SearchResult result : results) {
                var document = result.getDocument(SearchDocument.class);
                double rerankerScore = result.getSemanticSearch().getRerankerScore();
    
                System.out.printf("Search result #%d:%n", rowNumber++);
                System.out.printf("  Re-ranker Score: %.2f%n", rerankerScore);
                System.out.printf("  HotelName: %s%n", document.get("HotelName"));
                System.out.printf("  Description: %s%n%n",
                    document.get("Description") != null ?
                        document.get("Description") : "N/A");
    
                // Handle captions
                List<QueryCaptionResult> captions =
                    result.getSemanticSearch().getQueryCaptions();
                if (captions != null && !captions.isEmpty()) {
                    QueryCaptionResult caption = captions.get(0);
    
                    if (caption.getHighlights() != null &&
                        !caption.getHighlights().trim().isEmpty()) {
                        System.out.printf("  Caption with highlights: %s%n",
                            caption.getHighlights());
                    } else if (caption.getText() != null &&
                        !caption.getText().trim().isEmpty()) {
                        System.out.printf("  Caption text: %s%n",
                            caption.getText());
                    } else {
                        System.out.println(
                            "  Caption exists but has no text or highlights content");
                    }
                } else {
                    System.out.println("  No captions found for this result");
                }
                System.out.println("-".repeat(60));
            }
    
            System.exit(0);
        }
    }
    
  2. Compile e execute o código.

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticQueryWithCaptions"
    
  3. A saída deve incluir um novo elemento de legenda ao lado do campo de pesquisa. Legendas são as passagens mais relevantes em um resultado. Se o índice incluir partes maiores de texto, uma legenda será útil para extrair as frases mais interessantes.

    Search result #1:
      Re-ranker Score: 2.613231658935547
      HotelName: Uptown Chic Hotel
      Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
    
      Caption with highlights: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.
    

Retornar respostas semânticas

Nesta consulta final, retorne respostas semânticas.

O classificador semântico pode produzir uma resposta para uma cadeia de caracteres de consulta que tem as características de uma pergunta. A resposta gerada é extraída literalmente do seu conteúdo, portanto, não incluirá conteúdo composto como o que você pode esperar de um modelo de conclusão de chat.

Para produzir uma resposta semântica, a pergunta e a resposta devem estar alinhadas de perto e o modelo deve encontrar conteúdo que responda claramente à pergunta. Se as respostas potenciais não atenderem a um limite de confiança, o modelo não retornará uma resposta. Para fins de demonstração, a pergunta neste exemplo foi projetada para obter uma resposta para que você possa ver a sintaxe.

  1. Crie um SemanticAnswer.java arquivo no src/main/java/com/azure/search/quickstart diretório.

    package com.azure.search.quickstart;
    
    import com.azure.search.documents.SearchClientBuilder;
    import com.azure.search.documents.SearchDocument;
    import com.azure.search.documents.models.QueryAnswer;
    import com.azure.search.documents.models.QueryAnswerResult;
    import com.azure.search.documents.models.QueryAnswerType;
    import com.azure.search.documents.models.QueryCaption;
    import com.azure.search.documents.models.QueryCaptionResult;
    import com.azure.search.documents.models.QueryCaptionType;
    import com.azure.search.documents.models.QueryType;
    import com.azure.search.documents.models.SearchOptions;
    import com.azure.search.documents.models.SearchResult;
    import com.azure.search.documents.models.SemanticSearchOptions;
    import com.azure.search.documents.util.SearchPagedIterable;
    
    import java.util.List;
    
    public class SemanticAnswer {
        public static void main(String[] args) {
            var searchClient = new SearchClientBuilder()
                .endpoint(SearchConfig.SEARCH_ENDPOINT)
                .indexName(SearchConfig.INDEX_NAME)
                .credential(SearchConfig.CREDENTIAL)
                .buildClient();
    
            var searchOptions = new SearchOptions()
                .setQueryType(QueryType.SEMANTIC)
                .setSemanticSearchOptions(new SemanticSearchOptions()
                    .setSemanticConfigurationName(SearchConfig.SEMANTIC_CONFIG_NAME)
                    .setQueryCaption(new QueryCaption(QueryCaptionType.EXTRACTIVE))
                    .setQueryAnswer(new QueryAnswer(QueryAnswerType.EXTRACTIVE)))
                .setSelect("HotelName", "Description", "Category");
    
            SearchPagedIterable results = searchClient.search(
                "What's a good hotel for people who like to read",
                searchOptions, null);
    
            System.out.println("Answers:\n");
    
            // Extract semantic answers
            List<QueryAnswerResult> semanticAnswers =
                results.getSemanticResults().getQueryAnswers();
            int answerNumber = 1;
    
            if (semanticAnswers != null) {
                for (QueryAnswerResult answer : semanticAnswers) {
                    System.out.printf("Semantic answer result #%d:%n",
                        answerNumber++);
    
                    if (answer.getHighlights() != null &&
                        !answer.getHighlights().trim().isEmpty()) {
                        System.out.printf("Semantic Answer: %s%n",
                            answer.getHighlights());
                    } else {
                        System.out.printf("Semantic Answer: %s%n", answer.getText());
                    }
                    System.out.printf("Semantic Answer Score: %.2f%n%n",
                        answer.getScore());
                }
            }
    
            System.out.println("Search Results:\n");
            int rowNumber = 1;
    
            // Iterate through search results
            for (SearchResult result : results) {
                var document = result.getDocument(SearchDocument.class);
                double rerankerScore = result.getSemanticSearch().getRerankerScore();
    
                System.out.printf("Search result #%d:%n", rowNumber++);
                System.out.printf("Re-ranker Score: %.2f%n", rerankerScore);
                System.out.printf("Hotel: %s%n", document.get("HotelName"));
                System.out.printf("Description: %s%n",
                    document.get("Description") != null ?
                        document.get("Description") : "N/A");
    
                List<QueryCaptionResult> captions =
                    result.getSemanticSearch().getQueryCaptions();
                if (captions != null && !captions.isEmpty()) {
                    QueryCaptionResult caption = captions.get(0);
                    if (caption.getHighlights() != null &&
                        !caption.getHighlights().trim().isEmpty()) {
                        System.out.printf("Caption: %s%n%n",
                            caption.getHighlights());
                    } else {
                        System.out.printf("Caption: %s%n%n", caption.getText());
                    }
                } else {
                    System.out.println();
                }
            }
    
            System.exit(0);
        }
    }
    
  2. Compile e execute o código.

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticAnswer"
    
  3. A saída deve ser semelhante ao exemplo a seguir, em que a melhor resposta à pergunta é extraída de um dos resultados.

    Lembre-se de que as respostas são conteúdo verbatim extraído do índice e podem estar faltando frases que um usuário esperaria ver. Para obter respostas compostas geradas por um modelo de conclusão de chat, considere usar um padrão RAG ou recuperação agêntica.

    Semantic answer result #1:
    Semantic Answer: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
    Semantic Answer Score: 0.9829999804496765
    

Neste início rápido, você aprenderá a usar a classificação semântica adicionando uma configuração semântica a um índice de pesquisa e adicionando parâmetros semânticos a uma consulta. Você pode usar o índice de exemplo de hotéis (hotels-sample-index) ou um dos seus.

No Azure AI Search, a classificação semântica é a funcionalidade do lado da consulta que usa a compreensão de leitura de computador da Microsoft para pontuar os resultados da pesquisa, promovendo as correspondências mais semanticamente relevantes para o topo da lista. Dependendo do conteúdo e da consulta, a classificação semântica pode melhorar significativamente a relevância da pesquisa com o mínimo de esforço do desenvolvedor.

Você pode adicionar uma configuração semântica a um índice existente sem nenhum requisito de recompilação. A classificação semântica é mais eficaz em texto informativo ou descritivo.

Pré-requisitos

Configurar o acesso

É possível se conectar ao serviço Pesquisa de IA do Azure usando as chaves de API ou o Microsoft Entra ID com atribuições de função. É mais fácil usar as chaves para começar, mas as funções são mais seguras. Para obter mais informações, confira Conectar-se à Pesquisa de IA do Azure usando funções.

Para configurar o acesso baseado em função:

  1. Entre no portal do Azure e selecione seu serviço de pesquisa.

  2. No painel à esquerda, selecione Configurações>Chaves.

  3. No Controle de Acesso à API, selecione Controle de Acesso Baseado em Função ou Ambos se precisar de tempo para fazer a transição de clientes para acesso baseado em função.

  4. No painel esquerdo, selecione Controle de acesso (IAM).

  5. Selecione Adicionar>Adicionar atribuição de função.

  6. Atribua as funções de Colaborador do Serviço de Pesquisa e Colaborador de Dados do Índice de Pesquisa à sua conta de usuário.

Começar com um índice

Este início rápido pressupõe um índice existente e o modifica para incluir uma configuração semântica. Recomendamos o índice de exemplo de hotéis que você pode criar em minutos usando um assistente do portal do Azure.

Para começar com um índice existente:

  1. Entre no portal do Azure e localize seu serviço de pesquisa.

  2. EmGerenciamento de Pesquisa>Índices, selecione o hotéis-sample-index.

  3. Selecione configurações semânticas para garantir que o índice não tenha uma configuração semântica.

    Captura de tela de uma página de configuração semântica vazia no portal do Azure.

  4. Selecione o Gerenciador de Pesquisa e, em seguida, selecione o modo de exibição JSON.

  5. Cole os dados JSON abaixo no editor de consultas.

    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true
    }
    

    Captura de tela de uma consulta no Gerenciador de Pesquisa no portal.

  6. Selecione Pesquisar para executar a consulta.

    Essa consulta é uma pesquisa de palavra-chave. A resposta deve ser semelhante ao exemplo a seguir, conforme pontuação pelo classificador BM25 L1 padrão para pesquisa de texto completo.

    Para garantir a legibilidade, o exemplo seleciona apenas os campos HotelId, HotelName, e Description. Os resultados contêm correspondências verbais nos termos da consulta (walking, , distance, live) musicou variantes linguísticas (walk, living).

    "@odata.count": 13,
    "value": [
      {
        "@search.score": 5.5153193,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
      },
      {
        "@search.score": 5.074317,
        "HotelId": "24",
        "HotelName": "Uptown Chic Hotel",
        "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
      },
      {
        "@search.score": 4.8959594,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
      },
      {
        "@search.score": 2.5966604,
        "HotelId": "35",
        "HotelName": "Bellevue Suites",
        "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport."
      },
      {
        "@search.score": 2.566386,
        "HotelId": "47",
        "HotelName": "Country Comfort Inn",
        "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome."
      },
      {
        "@search.score": 2.2405157,
        "HotelId": "9",
        "HotelName": "Smile Up Hotel",
        "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene."
      },
      {
        "@search.score": 2.1737604,
        "HotelId": "8",
        "HotelName": "Foot Happy Suites",
        "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further."
      },
      {
        "@search.score": 2.0364518,
        "HotelId": "31",
        "HotelName": "Country Residence Hotel",
        "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
      },
      {
        "@search.score": 1.7595702,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
      },
      {
        "@search.score": 1.5502293,
        "HotelId": "15",
        "HotelName": "By the Market Hotel",
        "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
      },
      {
        "@search.score": 1.3302404,
        "HotelId": "42",
        "HotelName": "Rock Bottom Resort & Campground",
        "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away."
      },
      {
        "@search.score": 0.9050383,
        "HotelId": "38",
        "HotelName": "Lakeside B & B",
        "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
      },
      {
        "@search.score": 0.7334347,
        "HotelId": "39",
        "HotelName": "White Mountain Lodge & Suites",
        "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
      }
    ]
    

Esta consulta mostra a aparência da resposta antes da classificação semântica ser aplicada. Posteriormente, você pode executar a mesma consulta depois que a classificação semântica é configurada para ver como a resposta muda.

Dica

Você pode adicionar uma configuração semântica no portal do Azure. No entanto, se você quiser aprender a adicionar uma configuração semântica programaticamente, continue com este início rápido.

Configurar o cliente

No início rápido, use um notebook do Jupyter e a biblioteca azure-search-documents no SDK do Azure para Python para saber mais sobre classificação semântica.

Recomendamos o Visual Studio Code com o Python 3.10 ou posterior e a extensão python para este início rápido.

Dica

Você pode baixar um bloco de anotações concluído para começar com um projeto concluído ou seguir estas etapas para criar seu próprio.

É recomendável um ambiente virtual para este início rápido:

  1. Inicie o Visual Studio Code.

  2. Abra o arquivo semantic-search-quickstart.ipynb ou crie um novo bloco de anotações.

  3. Abra a Paleta de Comandos usando Ctrl+Shift+P.

  4. Pesquise por Python: criar ambiente.

  5. Selecione Venv.

  6. Selecione um interpretador do Python. Escolha 3.10 ou posterior.

Isso pode levar um minuto para ser configurado. Se você tiver problemas, confira Ambientes do Python no VS Code.

Instalar pacotes e definir variáveis de ambiente

  1. Instale pacotes, incluindo azure-search-documents.

    ! pip install -r requirements.txt --quiet
    
  2. Renomeie sample.env para .env, e forneça o ponto de extremidade do serviço de pesquisa. Você pode obter o endpoint no portal do Azure na página Visão geral do serviço de pesquisa.

    AZURE_SEARCH_ENDPOINT=https://your-search-service.search.windows.net
    AZURE_SEARCH_INDEX_NAME=hotels-sample-index
    

Entrar no Azure

Se você entrou no portal do Azure, está conectado ao Azure. Se você não tiver certeza, use a CLI do Azure ou o Azure PowerShell para fazer logon: az login ou az connect. Se você tiver vários locatários e assinaturas, consulte Início Rápido: Conectar sem chaves para obter ajuda sobre como se conectar.

Atualizar o índice

Nesta seção, você atualizará um índice de pesquisa para incluir uma configuração semântica. O código obtém a definição de índice do serviço de pesquisa e adiciona uma configuração semântica.

  1. Abra o arquivo semantic-search-quickstart.ipynb no Visual Studio Code ou crie um novo arquivo.

  2. Forneça as variáveis usadas na solução.

    # Provide variables
    from dotenv import load_dotenv
    from azure.identity import DefaultAzureCredential, get_bearer_token_provider
    import os
    
    load_dotenv(override=True) # Take environment variables from .env.
    
    # The following variables from your .env file are used in this notebook
    search_endpoint = os.environ["AZURE_SEARCH_ENDPOINT"]
    credential = DefaultAzureCredential()
    token_provider = get_bearer_token_provider(credential, "https://search.azure.com/.default")
    index_name = os.getenv("AZURE_SEARCH_INDEX", "hotels-sample-index")
    
  3. Crie um SearchIndexClient e obtenha o índice de exemplo de hotéis existente.

    from azure.search.documents.indexes import SearchIndexClient
    from azure.identity import DefaultAzureCredential
    import os
    
    # Initialize the client (similar to what you already have)
    search_endpoint = os.environ["AZURE_SEARCH_ENDPOINT"]
    credential = DefaultAzureCredential()
    index_name = "hotels-sample-index"  # or use your existing index_name variable
    
    # Create the SearchIndexClient
    index_client = SearchIndexClient(endpoint=search_endpoint, credential=credential)
    
    try:
        # Get the existing index schema
        index = index_client.get_index(index_name)
    
        print(f"Index name: {index.name}")
        print(f"Number of fields: {len(index.fields)}")
    
        # Print field details
        for field in index.fields:
            print(f"Field: {field.name}, Type: {field.type}, Searchable: {field.searchable}")
    
        # Access semantic configuration if it exists
        if index.semantic_search and index.semantic_search.configurations:
            for config in index.semantic_search.configurations:
                print(f"Semantic config: {config.name}")
                if config.prioritized_fields.title_field:
                    print(f"Title field: {config.prioritized_fields.title_field.field_name}")
        else:
            print("No semantic configuration exists for this index")
    
    except Exception as ex:
        print(f"Error retrieving index: {ex}")
    
  4. Execute o código.

  5. A saída é o nome do índice, da lista de campos e de uma instrução que indica se existe uma configuração semântica. Para fins deste início rápido, a mensagem deve dizer "Nenhuma configuração semântica existe para esse índice".

  6. Adicione uma configuração semântica a um índice de exemplo de hotéis existente em seu serviço de pesquisa. Nenhum documento de pesquisa é excluído por essa operação e seu índice ainda está operacional depois que a configuração é adicionada.

    # Add semantic configuration to hotels-sample-index and display updated index details
    from azure.search.documents.indexes.models import (
        SemanticConfiguration,
        SemanticField,
        SemanticPrioritizedFields,
        SemanticSearch
    )
    
    try:
        # Get the existing index
        existing_index = index_client.get_index(index_name)
    
        # Create a new semantic configuration
        new_semantic_config = SemanticConfiguration(
            name="semantic-config",
            prioritized_fields=SemanticPrioritizedFields(
                title_field=SemanticField(field_name="HotelName"),
                keywords_fields=[SemanticField(field_name="Tags")],
                content_fields=[SemanticField(field_name="Description")]
            )
        )
    
        # Add semantic configuration to the index
        if existing_index.semantic_search is None:
            existing_index.semantic_search = SemanticSearch(configurations=[new_semantic_config])
        else:
            # Check if configuration already exists
            config_exists = any(config.name == "semantic-config" 
                              for config in existing_index.semantic_search.configurations)
            if not config_exists:
                existing_index.semantic_search.configurations.append(new_semantic_config)
    
        # Update the index
        result = index_client.create_or_update_index(existing_index)
    
        # Get the updated index and display detailed information
        updated_index = index_client.get_index(index_name)
    
        print("Semantic configurations:")
        print("-" * 40)
        if updated_index.semantic_search and updated_index.semantic_search.configurations:
            for config in updated_index.semantic_search.configurations:
                print(f"  Configuration: {config.name}")
                if config.prioritized_fields.title_field:
                    print(f"    Title field: {config.prioritized_fields.title_field.field_name}")
                if config.prioritized_fields.keywords_fields:
                    keywords = [kf.field_name for kf in config.prioritized_fields.keywords_fields]
                    print(f"    Keywords fields: {', '.join(keywords)}")
                if config.prioritized_fields.content_fields:
                    content = [cf.field_name for cf in config.prioritized_fields.content_fields]
                    print(f"    Content fields: {', '.join(content)}")
                print()
        else:
            print("  No semantic configurations found")
    
        print("✅ Semantic configuration successfully added!")
    
    except Exception as ex:
        print(f"❌ Error adding semantic configuration: {ex}")
    
  7. Execute o código.

  8. A saída é a configuração semântica que você acabou de adicionar.

Executar consultas semânticas

Depois que o índice tiver uma configuração semântica, você poderá executar consultas que incluem parâmetros semânticos.

  1. Crie um SearchClient e uma solicitação de consulta que inclua o tipo de consulta semântica e a configuração semântica. Esse é o requisito mínimo para invocar a classificação semântica.

    # Set up the search client
    search_client = SearchClient(endpoint=search_endpoint,
                          index_name=index_name,
                          credential=credential)
    
    # Runs a semantic query (runs a BM25-ranked query, rescoring and promoting the most semantically relevant matches to the top)
    results =  search_client.search(query_type='semantic', semantic_configuration_name='semantic-config',
        search_text="walking distance to live music", 
        select='HotelId,HotelName,Description', query_caption='extractive')
    
    for result in results:
        print(result["@search.reranker_score"])
        print(result["HotelId"])
        print(result["HotelName"])
        print(f"Description: {result['Description']}")
    
  2. Execute o código.

  3. A saída deve consistir em 13 documentos, ordenados por "@search.reranker_score".

Legendas de retorno

Opcionalmente, você pode adicionar legendas para extrair partes do texto e aplicar o realce de clique aos termos e frases importantes. Essa consulta adiciona legendas.

  1. Adicione captions à consulta.

    # Runs a semantic query that returns captions
    results =  search_client.search(query_type='semantic', semantic_configuration_name='semantic-config',
        search_text="walking distance to live music", 
        select='HotelName,HotelId,Description', query_caption='extractive')
    
    for result in results:
        print(result["@search.reranker_score"])
        print(result["HotelId"])
        print(result["HotelName"])
        print(f"Description: {result['Description']}")
    
        captions = result["@search.captions"]
        if captions:
            caption = captions[0]
            if caption.highlights:
                print(f"Caption: {caption.highlights}\n")
            else:
                print(f"Caption: {caption.text}\n")
    
  2. Execute o código.

  3. A saída deve incluir um novo elemento de legenda ao lado do campo de pesquisa. Legendas são as passagens mais relevantes em um resultado. Se o índice incluir partes maiores de texto, uma legenda será útil para extrair as frases mais interessantes.

    2.613231658935547
    24
    Uptown Chic Hotel
    Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
    Caption: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.
    

Retornar respostas semânticas

Nesta consulta final, retorne respostas semânticas.

O classificador semântico pode produzir uma resposta para uma cadeia de caracteres de consulta que tem as características de uma pergunta. A resposta gerada é extraída literalmente do seu conteúdo, portanto, não incluirá conteúdo composto como o que você pode esperar de um modelo de conclusão de chat. Se a resposta semântica não for útil para seu cenário, você poderá omitir semantic_answers de seu código.

Para produzir uma resposta semântica, a pergunta e a resposta devem estar alinhadas de perto e o modelo deve encontrar conteúdo que responda claramente à pergunta. Se as respostas potenciais não atenderem a um limite de confiança, o modelo não retornará uma resposta. Para fins de demonstração, a pergunta neste exemplo foi projetada para obter uma resposta para que você possa ver a sintaxe.

  1. Adicione answers à consulta.

    # Run a semantic query that returns semantic answers  
    results =  search_client.search(query_type='semantic', semantic_configuration_name='semantic-config',
     search_text="what's a good hotel for people who like to read",
     select='HotelName,Description,Category', query_caption='extractive', query_answer="extractive",)
    
    semantic_answers = results.get_answers()
    for answer in semantic_answers:
        if answer.highlights:
            print(f"Semantic Answer: {answer.highlights}")
        else:
            print(f"Semantic Answer: {answer.text}")
        print(f"Semantic Answer Score: {answer.score}\n")
    
    for result in results:
        print(result["@search.reranker_score"])
        print(result["HotelName"])
        print(f"Description: {result['Description']}")
    
        captions = result["@search.captions"]
        if captions:
            caption = captions[0]
            if caption.highlights:
                print(f"Caption: {caption.highlights}\n")
            else:
                print(f"Caption: {caption.text}\n")
    
  2. Execute o código.

  3. A saída deve ser semelhante ao exemplo a seguir, em que a melhor resposta à pergunta é extraída de um dos resultados.

    Lembre-se de que as respostas são conteúdo verbatim extraído do índice e podem estar faltando frases que um usuário esperaria ver. Para obter respostas compostas geradas por um modelo de conclusão de chat, considere usar um padrão RAG ou recuperação agêntica.

    Semantic Answer: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
    Semantic Answer Score: 0.9829999804496765
    
    2.124817371368408
    1
    Stay-Kay City Hotel
    Description: This classic hotel is fully-refurbished and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.
    Caption: This classic hotel is<em> fully-refurbished </em>and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.
    
    2.0705394744873047
    16
    Double Sanctuary Resort
    Description: 5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.
    Caption: <em>5 star Luxury Hotel </em>-<em> Biggest </em>Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.
    
    2.041472911834717
    38
    Lakeside B & B
    Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
    Caption: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
    
    2.084540843963623
    Double Sanctuary Resort
    Description: 5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.
    Caption: <em>5 star Luxury Hotel </em>-<em> Biggest </em>Rooms in the<em> city. #1 </em>Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.
    
    ...
    

Neste início rápido, você aprenderá a usar a classificação semântica adicionando uma configuração semântica a um índice de pesquisa e adicionando parâmetros semânticos a uma consulta. Você pode usar o índice de exemplo de hotéis (hotels-sample-index) ou um dos seus.

No Azure AI Search, a classificação semântica é a funcionalidade do lado da consulta que usa a compreensão de leitura de computador da Microsoft para pontuar os resultados da pesquisa, promovendo as correspondências mais semanticamente relevantes para o topo da lista. Dependendo do conteúdo e da consulta, a classificação semântica pode melhorar significativamente a relevância da pesquisa com o mínimo de esforço do desenvolvedor.

Você pode adicionar uma configuração semântica a um índice existente sem nenhum requisito de recompilação. A classificação semântica é mais eficaz em texto informativo ou descritivo.

Pré-requisitos

Configurar o acesso

É possível se conectar ao serviço Pesquisa de IA do Azure usando as chaves de API ou o Microsoft Entra ID com atribuições de função. É mais fácil usar as chaves para começar, mas as funções são mais seguras. Para obter mais informações, confira Conectar-se à Pesquisa de IA do Azure usando funções.

Para configurar o acesso baseado em função:

  1. Entre no portal do Azure e selecione seu serviço de pesquisa.

  2. No painel à esquerda, selecione Configurações>Chaves.

  3. No Controle de Acesso à API, selecione Controle de Acesso Baseado em Função ou Ambos se precisar de tempo para fazer a transição de clientes para acesso baseado em função.

  4. No painel esquerdo, selecione Controle de acesso (IAM).

  5. Selecione Adicionar>Adicionar atribuição de função.

  6. Atribua as funções de Colaborador do Serviço de Pesquisa e Colaborador de Dados do Índice de Pesquisa à sua conta de usuário.

Começar com um índice

Este início rápido pressupõe um índice existente e o modifica para incluir uma configuração semântica. Recomendamos o índice de exemplo de hotéis que você pode criar em minutos usando um assistente do portal do Azure.

Para começar com um índice existente:

  1. Entre no portal do Azure e localize seu serviço de pesquisa.

  2. EmGerenciamento de Pesquisa>Índices, selecione o hotéis-sample-index.

  3. Selecione configurações semânticas para garantir que o índice não tenha uma configuração semântica.

    Captura de tela de uma página de configuração semântica vazia no portal do Azure.

  4. Selecione o Gerenciador de Pesquisa e, em seguida, selecione o modo de exibição JSON.

  5. Cole os dados JSON abaixo no editor de consultas.

    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true
    }
    

    Captura de tela de uma consulta no Gerenciador de Pesquisa no portal.

  6. Selecione Pesquisar para executar a consulta.

    Essa consulta é uma pesquisa de palavra-chave. A resposta deve ser semelhante ao exemplo a seguir, conforme pontuação pelo classificador BM25 L1 padrão para pesquisa de texto completo.

    Para garantir a legibilidade, o exemplo seleciona apenas os campos HotelId, HotelName, e Description. Os resultados contêm correspondências verbais nos termos da consulta (walking, , distance, live) musicou variantes linguísticas (walk, living).

    "@odata.count": 13,
    "value": [
      {
        "@search.score": 5.5153193,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
      },
      {
        "@search.score": 5.074317,
        "HotelId": "24",
        "HotelName": "Uptown Chic Hotel",
        "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
      },
      {
        "@search.score": 4.8959594,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
      },
      {
        "@search.score": 2.5966604,
        "HotelId": "35",
        "HotelName": "Bellevue Suites",
        "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport."
      },
      {
        "@search.score": 2.566386,
        "HotelId": "47",
        "HotelName": "Country Comfort Inn",
        "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome."
      },
      {
        "@search.score": 2.2405157,
        "HotelId": "9",
        "HotelName": "Smile Up Hotel",
        "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene."
      },
      {
        "@search.score": 2.1737604,
        "HotelId": "8",
        "HotelName": "Foot Happy Suites",
        "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further."
      },
      {
        "@search.score": 2.0364518,
        "HotelId": "31",
        "HotelName": "Country Residence Hotel",
        "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
      },
      {
        "@search.score": 1.7595702,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
      },
      {
        "@search.score": 1.5502293,
        "HotelId": "15",
        "HotelName": "By the Market Hotel",
        "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
      },
      {
        "@search.score": 1.3302404,
        "HotelId": "42",
        "HotelName": "Rock Bottom Resort & Campground",
        "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away."
      },
      {
        "@search.score": 0.9050383,
        "HotelId": "38",
        "HotelName": "Lakeside B & B",
        "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
      },
      {
        "@search.score": 0.7334347,
        "HotelId": "39",
        "HotelName": "White Mountain Lodge & Suites",
        "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
      }
    ]
    

Esta consulta mostra a aparência da resposta antes da classificação semântica ser aplicada. Posteriormente, você pode executar a mesma consulta depois que a classificação semântica é configurada para ver como a resposta muda.

Dica

Você pode adicionar uma configuração semântica no portal do Azure. No entanto, se você quiser aprender a adicionar uma configuração semântica programaticamente, continue com este início rápido.

Configurar o cliente

Neste início rápido, você usará um cliente REST e as APIs REST do Azure AI Search para configurar e usar um classificador semântico.

Recomendamos o Visual Studio Code com uma extensão de cliente REST para este início rápido.

Dica

É possível baixar o código-fonte para começar com um projeto concluído, ou seguir as etapas neste artigo para criar o seu.

  1. Inicie o Visual Studio Code e abra o arquivo semantic-search-index-update.rest ou crie um novo arquivo.

  2. Na parte superior, defina variáveis de ambiente para seu serviço de pesquisa, autorização e nome do índice.

    • Para @searchURL, acesse o portal do Azure e copie a URL da página de Visão Geral do serviço Pesquisa.

    • Para @personalAccessToken, siga as instruções em Conectar sem chaves para obter o token de acesso pessoal.

  3. Para testar a conexão, envie sua primeira solicitação.

    ### List existing indexes by name (verify the connection)
     GET  {{searchUrl}}/indexes?api-version=2025-09-01&$select=name  HTTP/1.1
     Authorization: Bearer {{personalAccessToken}}
    
  4. Selecione Enviar solicitação.

    Captura de tela do link de solicitação de envio do cliente REST.

  5. A saída dessa solicitação GET retorna uma lista de índices existentes. Você deve receber um código de status HTTP 200 Sucesso e uma lista de índices, incluindo o hotels-sample-index usado neste guia rápido.

Atualizar o índice

Para atualizar um índice usando a API REST, você deve fornecer todo o esquema, além das modificações que deseja fazer. Essa solicitação fornece o esquema hotels-sample-index, além da configuração semântica. A modificação consiste no JSON a seguir.

"semantic": {
   "configurations": [
   {
      "name": "semantic-config",
      "rankingOrder": "BoostedRerankerScore",
      "prioritizedFields": {
         "titleField": { "fieldName": "HotelName" },
         "prioritizedContentFields": [{ "fieldName": "Description" }],
         "prioritizedKeywordsFields": [{ "fieldName": "Tags" }]
      }
   }
   ]
}
  1. Formular uma solicitação PUT especificando o nome do índice, a operação e o esquema JSON completo. Todos os elementos necessários do esquema devem estar presentes. Essa solicitação inclui o esquema completo para hotels-sample-index mais a configuração semântica.

    PUT {{searchUrl}}/indexes/hotels-sample-index?api-version=2025-09-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{personalAccessToken}}
    
    {
       "name": "hotels-sample-index",
       "fields": [
           { "name": "HotelId", "type": "Edm.String", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "key": true },
           { "name": "HotelName", "type": "Edm.String", "searchable": true, "filterable": false, "retrievable": true, "stored": true, "sortable": false, "facetable": false, "analyzer": "en.microsoft" },
           { "name": "Description", "type": "Edm.String", "searchable": true, "filterable": false, "retrievable": true, "stored": true, "sortable": false, "facetable": false, "analyzer": "en.microsoft" },
           { "name": "Description_fr", "type": "Edm.String", "searchable": true, "filterable": false, "retrievable": true, "stored": true, "sortable": false, "facetable": false, "analyzer": "fr.microsoft" },
           { "name": "Category", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
           { "name": "Tags", "type": "Collection(Edm.String)", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
           { "name": "ParkingIncluded", "type": "Edm.Boolean", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true },
           { "name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "searchable": false, "filterable": false, "retrievable": true, "stored": true, "sortable": true, "facetable": false },
           { "name": "Rating", "type": "Edm.Double", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": true, "facetable": true },
           { "name": "Address", "type": "Edm.ComplexType", "fields": [
              { "name": "StreetAddress", "type": "Edm.String", "searchable": true, "filterable": false, "retrievable": true, "stored": true, "sortable": false, "facetable": false, "analyzer": "en.microsoft" },
              { "name": "City", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
              { "name": "StateProvince", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
              { "name": "PostalCode", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
              { "name": "Country", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" }]},
           { "name": "Location", "type": "Edm.GeographyPoint", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": true, "facetable": false },
           { "name": "Rooms", "type": "Collection(Edm.ComplexType)", "fields": [
              { "name": "Description", "type": "Edm.String", "searchable": true, "filterable": false, "retrievable": true, "stored": true, "sortable": false, "facetable": false, "analyzer": "en.microsoft" },
              { "name": "Description_fr", "type": "Edm.String", "searchable": true, "filterable": false, "retrievable": true, "stored": true, "sortable": false, "facetable": false, "analyzer": "fr.microsoft" },
              { "name": "Type", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
              { "name": "BaseRate", "type": "Edm.Double", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true },
              { "name": "BedOptions", "type": "Edm.String", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" },
              { "name": "SleepsCount", "type": "Edm.Int64", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true },
              { "name": "SmokingAllowed", "type": "Edm.Boolean", "searchable": false, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true },
              { "name": "Tags", "type": "Collection(Edm.String)", "searchable": true, "filterable": true, "retrievable": true, "stored": true, "sortable": false, "facetable": true, "analyzer": "en.microsoft" }]},
           { "name": "id", "type": "Edm.String", "searchable": false, "filterable": false, "retrievable": false, "stored": true, "sortable": false, "facetable": false },
           { "name": "rid", "type": "Edm.String", "searchable": false, "filterable": false, "retrievable": false, "stored": true, "sortable": false, "facetable": false }],
      "scoringProfiles": [],
      "suggesters": [],
      "analyzers": [],
      "normalizers": [],
      "tokenizers": [],
      "tokenFilters": [],
      "charFilters": [],
      "similarity": {
        "@odata.type": "#Microsoft.Azure.Search.BM25Similarity"
      },
      "semantic": {
        "configurations": [
          {
            "name": "semantic-config",
            "rankingOrder": "BoostedRerankerScore",
            "prioritizedFields": {
              "titleField": {
                "fieldName": "HotelName"
              },
              "prioritizedContentFields": [
                {
                  "fieldName": "Description"
                }
              ],
              "prioritizedKeywordsFields": [
                {
                  "fieldName": "Tags"
                }
              ]
            }
          }
        ]
      }
    }
    
  2. Selecione Enviar solicitação.

  3. A saída dessa solicitação POST é uma HTTP 200 Success mensagem de status.

Executar consultas semânticas

Os parâmetros semânticos necessários incluem query_type e semantic_configuration_name. Aqui está um exemplo de uma consulta semântica básica usando os parâmetros mínimos.

  1. Abra o arquivo semantic-search-query.rest ou crie um novo arquivo.

  2. Na parte superior do arquivo, defina variáveis de ambiente para seu serviço de pesquisa, autorização e nome do índice.

    • Para @searchURL, acesse o portal do Azure e copie a URL da página de Visão Geral do serviço Pesquisa.

    • Para @personalAccessToken, siga as instruções em Conectar sem chaves para obter o token de acesso pessoal.

  3. Teste a conexão com uma solicitação GET que retorna o índice de exemplo de hotéis.

    GET {{searchUrl}}/indexes/hotels-sample-index?api-version=2025-09-01  HTTP/1.1
    Authorization: Bearer {{personalAccessToken}}
    
  4. Envie uma consulta que inclua o tipo de consulta semântica e o nome de configuração.

     POST {{searchUrl}}/indexes/hotels-sample-index/docs/search?api-version=2025-09-01  HTTP/1.1
     Content-Type: application/json
     Authorization: Bearer {{personalAccessToken}}
    
     {
       "search": "walking distance to live music",
       "select": "HotelId, HotelName, Description",
       "count": true,
       "top": 7,
       "queryType": "simple"
     }
    
  5. A saída consiste em resultados da pesquisa JSON. Treze hotéis correspondem à consulta. Os sete primeiros estão incluídos neste exemplo.

    {
       "@odata.count": 13,
       "@search.answers": [],
       "value": [
         {
           "@search.score": 5.074317,
           "@search.rerankerScore": 2.613231658935547,
           "HotelId": "24",
           "HotelName": "Uptown Chic Hotel",
           "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
         },
         {
           "@search.score": 5.5153193,
           "@search.rerankerScore": 2.271434783935547,
           "HotelId": "2",
           "HotelName": "Old Century Hotel",
           "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
         },
         {
           "@search.score": 4.8959594,
           "@search.rerankerScore": 1.9861756563186646,
           "HotelId": "4",
           "HotelName": "Sublime Palace Hotel",
           "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
         },
         {
           "@search.score": 0.7334347,
           "@search.rerankerScore": 1.9615401029586792,
           "HotelId": "39",
           "HotelName": "White Mountain Lodge & Suites",
           "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
         },
         {
           "@search.score": 1.5502293,
           "@search.rerankerScore": 1.9085469245910645,
           "HotelId": "15",
           "HotelName": "By the Market Hotel",
           "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
         },
         {
           "@search.score": 1.7595702,
           "@search.rerankerScore": 1.90234375,
           "HotelId": "49",
           "HotelName": "Swirling Currents Hotel",
           "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
         },
         {
           "@search.score": 2.0364518,
           "@search.rerankerScore": 1.9012802839279175,
           "HotelId": "31",
           "HotelName": "Country Residence Hotel",
           "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
         }
       ]
     }
    

Legendas de retorno

Opcionalmente, você pode adicionar legendas para extrair partes do texto e aplicar o realce de clique aos termos e frases importantes. Essa consulta adiciona legendas que incluem realce de clique.

  1. Adicione o captions parâmetro e envie a solicitação.

    POST {{searchUrl}}/indexes/hotels-sample-index/docs/search?api-version=2025-09-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{personalAccessToken}}
    
    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true,
      "queryType": "semantic",
      "semanticConfiguration": "semantic-config",
      "captions": "extractive|highlight-true"
    }
    
  2. A saída consiste nos mesmos resultados, com a adição de "@search.captions". Aqui está o JSON para um único documento. Cada correspondência inclui pontuações de pesquisa, legendas em texto sem formatação e formatação de realce, além dos campos selecionados.

    {
       "@search.score": 5.074317,
       "@search.rerankerScore": 2.613231658935547,
       "@search.captions": [
         {
           "text": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.",
           "highlights": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance."
         }
       ],
       "HotelId": "24",
       "HotelName": "Uptown Chic Hotel",
       "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
    }
    

Retornar respostas semânticas

Nesta consulta final, retorne respostas semânticas.

O classificador semântico pode produzir uma resposta para uma cadeia de caracteres de consulta que tem as características de uma pergunta. A resposta gerada é extraída literalmente do seu conteúdo, portanto, não incluirá conteúdo composto como o que você pode esperar de um modelo de conclusão de chat. Se a resposta semântica não for útil para seu cenário, você poderá omitir semantic_answers de seu código.

Para produzir uma resposta semântica, a pergunta e a resposta devem estar alinhadas de perto e o modelo deve encontrar conteúdo que responda claramente à pergunta. Se as respostas potenciais não atenderem a um limite de confiança, o modelo não retornará uma resposta. Para fins de demonstração, a pergunta neste exemplo foi projetada para obter uma resposta para que você possa ver a sintaxe.

  1. Formular a solicitação usando uma cadeia de caracteres de pesquisa que faz uma pergunta.

    POST {{searchUrl}}/indexes/hotels-sample-index/docs/search?api-version=2025-09-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{personalAccessToken}}
    
    {
      "search": "what's a good hotel for people who like to read",
      "select": "HotelId, HotelName, Description",
      "count": true,
      "queryType": "semantic",
      "semanticConfiguration": "semantic-config"
      "answers": "extractive"
    }
    
  2. A saída consiste em 41 resultados para a nova consulta, com "@search.answers" para a pergunta na consulta sobre hotéis para pessoas que gostam de ler.

    Lembre-se de que as respostas são conteúdo verbatim extraído do índice e podem estar faltando frases que um usuário esperaria ver. Para obter respostas compostas geradas por um modelo de conclusão de chat, considere usar um padrão RAG ou recuperação agêntica.

    Neste exemplo, a resposta é considerada muito adequada para a pergunta.

    {
      "@odata.count": 41,
      "@search.answers": [
        {
          "key": "38",
          "text": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.",
          "highlights": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.",
          "score": 0.9829999804496765
        }
      ],
      "value": [
        {
          "@search.score": 2.0361428,
          "@search.rerankerScore": 2.124817371368408,
          "HotelId": "1",
          "HotelName": "Stay-Kay City Hotel",
          "Description": "This classic hotel is fully-refurbished and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities."
        },
        {
          "@search.score": 3.759768,
          "@search.rerankerScore": 2.0705394744873047,
          "HotelId": "16",
          "HotelName": "Double Sanctuary Resort",
          "Description": "5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room."
        },
        {
          "@search.score": 0.7308748,
          "@search.rerankerScore": 2.041472911834717,
          "HotelId": "38",
          "HotelName": "Lakeside B & B",
          "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
        },
        {
          "@search.score": 3.391012,
          "@search.rerankerScore": 2.0231292247772217,
          "HotelId": "2",
          "HotelName": "Old Century Hotel",
          "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
        },
        {
          "@search.score": 1.3198771,
          "@search.rerankerScore": 2.021622657775879,
          "HotelId": "15",
          "HotelName": "By the Market Hotel",
          "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
        },
        {
          "@search.score": 1.3983066,
          "@search.rerankerScore": 2.005582809448242,
          "HotelId": "5",
          "HotelName": "Red Tide Hotel",
          "Description": "On entering this charming hotel in Scarlet Harbor, you'll notice an uncommon blend of antiques, original artwork, and contemporary comforts that give this hotel its signature look. Each suite is furnished to accentuate the views and unique characteristics of the building's classic architecture. No two suites are alike. However, all guests are welcome in the mezzanine plaza, the surrounding gardens, and the northside terrace for evening refreshments."
        },
        {
          "@search.score": 1.4815493,
          "@search.rerankerScore": 1.9739465713500977,
          "HotelId": "24",
          "HotelName": "Uptown Chic Hotel",
          "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
        }
      ]
    }
    

Neste início rápido, você aprenderá a usar a classificação semântica adicionando uma configuração semântica a um índice de pesquisa e adicionando parâmetros semânticos a uma consulta. Você pode usar o índice de exemplo de hotéis (hotels-sample-index) ou um dos seus.

No Azure AI Search, a classificação semântica é a funcionalidade do lado da consulta que usa a compreensão de leitura de computador da Microsoft para pontuar os resultados da pesquisa, promovendo as correspondências mais semanticamente relevantes para o topo da lista. Dependendo do conteúdo e da consulta, a classificação semântica pode melhorar significativamente a relevância da pesquisa com o mínimo de esforço do desenvolvedor.

Você pode adicionar uma configuração semântica a um índice existente sem nenhum requisito de recompilação. A classificação semântica é mais eficaz em texto informativo ou descritivo.

Pré-requisitos

Configurar o acesso

É possível se conectar ao serviço Pesquisa de IA do Azure usando as chaves de API ou o Microsoft Entra ID com atribuições de função. É mais fácil usar as chaves para começar, mas as funções são mais seguras. Para obter mais informações, confira Conectar-se à Pesquisa de IA do Azure usando funções.

Para configurar o acesso baseado em função:

  1. Entre no portal do Azure e selecione seu serviço de pesquisa.

  2. No painel à esquerda, selecione Configurações>Chaves.

  3. No Controle de Acesso à API, selecione Controle de Acesso Baseado em Função ou Ambos se precisar de tempo para fazer a transição de clientes para acesso baseado em função.

  4. No painel esquerdo, selecione Controle de acesso (IAM).

  5. Selecione Adicionar>Adicionar atribuição de função.

  6. Atribua as funções de Colaborador do Serviço de Pesquisa e Colaborador de Dados do Índice de Pesquisa à sua conta de usuário.

Começar com um índice

Este início rápido pressupõe um índice existente e o modifica para incluir uma configuração semântica. Recomendamos o índice de exemplo de hotéis que você pode criar em minutos usando um assistente do portal do Azure.

Para começar com um índice existente:

  1. Entre no portal do Azure e localize seu serviço de pesquisa.

  2. EmGerenciamento de Pesquisa>Índices, selecione o hotéis-sample-index.

  3. Selecione configurações semânticas para garantir que o índice não tenha uma configuração semântica.

    Captura de tela de uma página de configuração semântica vazia no portal do Azure.

  4. Selecione o Gerenciador de Pesquisa e, em seguida, selecione o modo de exibição JSON.

  5. Cole os dados JSON abaixo no editor de consultas.

    {
      "search": "walking distance to live music",
      "select": "HotelId, HotelName, Description",
      "count": true
    }
    

    Captura de tela de uma consulta no Gerenciador de Pesquisa no portal.

  6. Selecione Pesquisar para executar a consulta.

    Essa consulta é uma pesquisa de palavra-chave. A resposta deve ser semelhante ao exemplo a seguir, conforme pontuação pelo classificador BM25 L1 padrão para pesquisa de texto completo.

    Para garantir a legibilidade, o exemplo seleciona apenas os campos HotelId, HotelName, e Description. Os resultados contêm correspondências verbais nos termos da consulta (walking, , distance, live) musicou variantes linguísticas (walk, living).

    "@odata.count": 13,
    "value": [
      {
        "@search.score": 5.5153193,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music."
      },
      {
        "@search.score": 5.074317,
        "HotelId": "24",
        "HotelName": "Uptown Chic Hotel",
        "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance."
      },
      {
        "@search.score": 4.8959594,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience."
      },
      {
        "@search.score": 2.5966604,
        "HotelId": "35",
        "HotelName": "Bellevue Suites",
        "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport."
      },
      {
        "@search.score": 2.566386,
        "HotelId": "47",
        "HotelName": "Country Comfort Inn",
        "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome."
      },
      {
        "@search.score": 2.2405157,
        "HotelId": "9",
        "HotelName": "Smile Up Hotel",
        "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene."
      },
      {
        "@search.score": 2.1737604,
        "HotelId": "8",
        "HotelName": "Foot Happy Suites",
        "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further."
      },
      {
        "@search.score": 2.0364518,
        "HotelId": "31",
        "HotelName": "Country Residence Hotel",
        "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door."
      },
      {
        "@search.score": 1.7595702,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. "
      },
      {
        "@search.score": 1.5502293,
        "HotelId": "15",
        "HotelName": "By the Market Hotel",
        "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service."
      },
      {
        "@search.score": 1.3302404,
        "HotelId": "42",
        "HotelName": "Rock Bottom Resort & Campground",
        "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away."
      },
      {
        "@search.score": 0.9050383,
        "HotelId": "38",
        "HotelName": "Lakeside B & B",
        "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply."
      },
      {
        "@search.score": 0.7334347,
        "HotelId": "39",
        "HotelName": "White Mountain Lodge & Suites",
        "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings."
      }
    ]
    

Esta consulta mostra a aparência da resposta antes da classificação semântica ser aplicada. Posteriormente, você pode executar a mesma consulta depois que a classificação semântica é configurada para ver como a resposta muda.

Dica

Você pode adicionar uma configuração semântica no portal do Azure. No entanto, se você quiser aprender a adicionar uma configuração semântica programaticamente, continue com este início rápido.

Configurar o cliente

Neste início rápido, você usará um IDE e a biblioteca de clientes @azure/search-documents para adicionar classificação semântica a um índice de pesquisa existente.

O início rápido pressupõe que o seguinte está disponível em seu computador:

Dica

É possível baixar o código-fonte para começar com um projeto concluído, ou seguir as etapas neste artigo para criar o seu.

Configurar o ambiente de desenvolvimento local

  1. Inicie o Visual Studio Code em um novo diretório.

    mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart
    code .
    
  2. Crie um novo pacote para módulos de ESM no diretório do projeto.

    npm init -y
    npm pkg set type=module
    
  3. Instale pacotes de desenvolvimento, incluindo azure-search-documents.

    npm install @azure/identity @azure/search-documents dotenv
    
  4. Instalar pacotes de dependência de desenvolvimento.

    npm install dotenv @types/node --save-dev
    
  5. Crie um arquivo tsconfig.json no diretório do projeto para habilitar módulos de ESM e definir a resolução do módulo.

     {
       "compilerOptions": {
         "target": "es2022",
         "module": "esnext",
         "moduleResolution": "bundler",
         "rootDir": "./src",
         "outDir": "./dist/",
         "esModuleInterop": true,
         "forceConsistentCasingInFileNames": true,
         "strict": true,
         "skipLibCheck": true,
         "declaration": true,
         "sourceMap": true,
         "resolveJsonModule": true,
         "moduleDetection": "force",
         "allowSyntheticDefaultImports": true,
         "verbatimModuleSyntax": false
       },
       "include": [
         "src/**/*.ts"
       ],
       "exclude": [
         "node_modules/**/*",
         "**/*.spec.ts"
       ]
     }
    
  6. Atualize package.json para incluir um script para a criação de arquivos TypeScript. Adicione a seguinte linha à seção scripts.

    "build": "tsc"
    
  7. Crie .env e forneça o ponto de extremidade do serviço de pesquisa. Você pode obter o endpoint no portal do Azure na página Visão geral do serviço de pesquisa.

    AZURE_SEARCH_ENDPOINT=YOUR-SEARCH-SERVICE-ENDPOINT
    AZURE_SEARCH_INDEX_NAME=hotels-sample-index
    SEMANTIC_CONFIGURATION_NAME=semantic-config
    
  8. Crie um diretório src no diretório do projeto.

    mkdir src
    

Entrar no Azure

Se você entrou no portal do Azure, está conectado ao Azure. Se você não tiver certeza, use a CLI do Azure ou o Azure PowerShell para fazer logon: az login ou az connect. Se você tiver vários locatários e assinaturas, consulte Início Rápido: Conectar sem chaves para obter ajuda sobre como se conectar.

Criar um arquivo de autenticação comum

Crie um arquivo em ./src chamado config.ts para fazer a leitura do arquivo .env e manter as variáveis de ambiente e a credencial de autenticação. Copie no código a seguir; não altere-o. Esse arquivo será usado por todos os outros arquivos neste início rápido.

import { DefaultAzureCredential } from "@azure/identity";

// Configuration - use environment variables
export const searchEndpoint = process.env.AZURE_SEARCH_ENDPOINT || "PUT-YOUR-SEARCH-SERVICE-ENDPOINT-HERE";
export const indexName = process.env.AZURE_SEARCH_INDEX_NAME || "hotels-sample-index";
export const semanticConfigurationName = process.env.SEMANTIC_CONFIGURATION_NAME || "semantic-config";

// Create credential
export const credential = new DefaultAzureCredential();

console.log(`Using Azure Search endpoint: ${searchEndpoint}`);
console.log(`Using index name: ${indexName}\n\n`);

// Hotel document interface
export interface HotelDocument {
    "@search.action"?: string;
    HotelId: string;
    HotelName: string;
    Description: string;
    Category: string;
    Tags: string[];
    ParkingIncluded: string;
    LastRenovationDate: string;
    Rating: number;
    Address: {
        StreetAddress: string;
        City: string;
        StateProvince: string;
        PostalCode: string;
        Country: string;
    };
}

Obter o esquema de índice

Nesta seção, você obterá as configurações para o índice hotels-sample-index existente em seu serviço de pesquisa.

  1. Crie um arquivo em ./src chamado getIndexSettings.ts e copie o código a seguir.

    import {
        SearchIndexClient
    } from "@azure/search-documents";
    import { searchEndpoint, indexName, credential } from "./config.js";
    
    const indexClient = new SearchIndexClient(searchEndpoint, credential);
    
    console.log('Updating semantic search index...');
    
    // Get the existing schema
    const index = await indexClient.getIndex(indexName);
    
    console.log(`Index name: ${index.name}`);
    console.log(`Number of fields: ${index.fields.length}`);
    
    for(const field of index.fields) {
    
        // @ts-ignore
        console.log(`Field: ${field.name}, Type: ${field.type}, Searchable: ${field.searchable}`);
    }
    
    if(index.semanticSearch && index.semanticSearch.configurations) {
        console.log(`Semantic search configurations: ${index.semanticSearch.configurations.length}`);
        for(const config of index.semanticSearch.configurations) {
            console.log(`Configuration name: ${config.name}`);
            console.log(`Title field: ${config.prioritizedFields.titleField?.name}`);
        }
    } else {
        console.log("No semantic configuration exists for this index.");
    }
    
  2. Execute o código.

    npm run build && node -r dotenv/config dist/getIndexSettings.js
    
  3. A saída é o nome do índice, da lista de campos e de uma instrução que indica se existe uma configuração semântica. Para os propósitos deste início rápido, a mensagem deve dizer No semantic configuration exists for this index.

Atualizar o índice com uma configuração semântica

  1. Crie um arquivo em ./src chamado updateIndexSettings.ts e copie o código a seguir para adicionar uma configuração semântica ao índice hotels-sample-index existente em seu serviço de pesquisa. Nenhum documento de pesquisa é excluído por essa operação e seu índice ainda está operacional depois que a configuração é adicionada.

    import {
        SearchIndexClient,
        SemanticConfiguration,
        SemanticPrioritizedFields,
        SemanticField
    } from "@azure/search-documents";
    import { searchEndpoint, indexName, credential, semanticConfigurationName } from "./config.js";
    
    try {
    
        const indexClient = new SearchIndexClient(searchEndpoint, credential);
    
        const existingIndex = await indexClient.getIndex(indexName);
    
        const fields: SemanticPrioritizedFields = {
            titleField: {
                name: "HotelName"
            },
            keywordsFields: [{
                name: "Tags"
            }] as SemanticField[],
            contentFields: [{
                name: "Description"
            }] as SemanticField[]
        }
    
        const newSemanticConfiguration: SemanticConfiguration = {
            name: semanticConfigurationName,
            prioritizedFields: fields
        };
    
        // Add the new semantic configuration to the existing index
        if (existingIndex.semanticSearch && existingIndex.semanticSearch.configurations) {
            existingIndex.semanticSearch.configurations.push(newSemanticConfiguration);
        } else {
            const configExists = existingIndex.semanticSearch?.configurations?.some(
                config => config.name === semanticConfigurationName
            );
            if (!configExists) {
                existingIndex.semanticSearch = {
                    configurations: [newSemanticConfiguration]
                };
            }
        }
    
        await indexClient.createOrUpdateIndex(existingIndex);
    
        const updatedIndex = await indexClient.getIndex(indexName);
    
        console.log(`Semantic configurations:`);
        console.log("-".repeat(40));
    
        if (updatedIndex.semanticSearch && updatedIndex.semanticSearch.configurations) {
            for (const config of updatedIndex.semanticSearch.configurations) {
                console.log(`Configuration name: ${config.name}`);
                console.log(`Title field: ${config.prioritizedFields.titleField?.name}`);
                console.log(`Keywords fields: ${config.prioritizedFields.keywordsFields?.map(f => f.name).join(", ")}`);
                console.log(`Content fields: ${config.prioritizedFields.contentFields?.map(f => f.name).join(", ")}`);
                console.log("-".repeat(40));
            }
        } else {
            console.log("No semantic configurations found.");
        }
    
        console.log("Semantic configuration updated successfully.");
    } catch (error) {
        console.error("Error updating semantic configuration:", error);
    }
    
  2. Execute o código.

    npm run build && node -r dotenv/config dist/updateIndexSettings.js
    
  3. A saída é a configuração semântica que você acabou de adicionar. Semantic configuration updated successfully.

Executar consultas semânticas

Depois que o índice hotels-sample-index tiver uma configuração semântica, você poderá executar consultas que incluem parâmetros semânticos.

  1. Crie um arquivo em ./src chamado semanticQuery.ts e copie o código a seguir para criar uma consulta semântica do índice. Esse é o requisito mínimo para invocar a classificação semântica.

    import { SearchClient } from "@azure/search-documents";
    import { HotelDocument, credential, searchEndpoint, indexName, semanticConfigurationName } from "./config.js";
    
    const searchClient = new SearchClient<HotelDocument>(
        searchEndpoint,
        indexName,
        credential
    );
    
    const results = await searchClient.search("walking distance to live music", {
        queryType: "semantic",
        semanticSearchOptions: {
            configurationName: semanticConfigurationName
        },
        select: ["HotelId", "HotelName", "Description"]
    });
    
    let rowNumber = 1;
    for await (const result of results.results) {
    
        // Log each result
        const doc = result.document;
        const score = result.score;
        const rerankerScoreDisplay = result.rerankerScore;
    
        console.log(`Search result #${rowNumber++}:`);
        console.log(`  Re-ranker Score: ${rerankerScoreDisplay}`);
        console.log(`  HotelId: ${doc.HotelId}`);
        console.log(`  HotelName: ${doc.HotelName}`);
        console.log(`  Description: ${doc.Description || 'N/A'}\n`);
    }
    
  2. Execute o código.

    npm run build && node -r dotenv/config dist/semanticQuery.js
    
  3. A saída deve consistir em 13 documentos, ordenados por rerankerScoreDisplay.

Legendas de retorno

Opcionalmente, você pode adicionar legendas para extrair partes do texto e aplicar o realce de clique aos termos e frases importantes. Essa consulta adiciona legendas.

  1. Crie um arquivo em ./src chamado semanticQueryReturnCaptions.ts e copie o código a seguir para adicionar legendas à consulta.

    import { SearchClient } from "@azure/search-documents";
    import { HotelDocument, credential, searchEndpoint, indexName, semanticConfigurationName } from "./config.js";
    
    const searchClient = new SearchClient<HotelDocument>(
        searchEndpoint,
        indexName,
        credential
    );
    
    // Debug info
    console.log(`Using semantic configuration: ${semanticConfigurationName}`);
    console.log("Search query: walking distance to live music");
    
    const results = await searchClient.search("walking distance to live music", {
        queryType: "semantic",
        semanticSearchOptions: {
            configurationName: semanticConfigurationName,
            captions: {
                captionType: "extractive",
                highlight: true
            }
        },
        select: ["HotelId", "HotelName", "Description"],
    });
    
    console.log(`Found ${results.count} results with semantic search\n`);
    let rowNumber = 1;
    
    for await (const result of results.results) {
        // Log each result
        const doc = result.document;
        const rerankerScoreDisplay = result.rerankerScore;
    
        console.log(`Search result #${rowNumber++}:`);
        console.log(`  Re-ranker Score: ${rerankerScoreDisplay}`);
        console.log(`  HotelName: ${doc.HotelName}`);
        console.log(`  Description: ${doc.Description || 'N/A'}\n`);
    
        // Caption handling with better debugging
        const captions = result.captions;
    
        if (captions && captions.length > 0) {
            const caption = captions[0];
    
            if (caption.highlights) {
                console.log(`  Caption with highlights: ${caption.highlights}`);
            } else if (caption.text) {
                console.log(`  Caption text: ${caption.text}`);
            } else {
                console.log(`  Caption exists but has no text or highlights content`);
            }
        } else {
            console.log("  No captions found for this result");
        }
        console.log("-".repeat(60));
    }
    
  2. Execute o código.

    npm run build && node -r dotenv/config dist/semanticQueryReturnCaptions.js
    
  3. A saída deve incluir um novo elemento de legenda ao lado do campo de pesquisa. Legendas são as passagens mais relevantes em um resultado. Se o índice incluir partes maiores de texto, uma legenda será útil para extrair as frases mais interessantes.

    Search result #1:
      Re-ranker Score: 2.613231658935547
      HotelName: Uptown Chic Hotel
      Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
    
      Caption with highlights: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.
    

Retornar respostas semânticas

Nesta consulta final, retorne respostas semânticas.

O classificador semântico pode produzir uma resposta para uma cadeia de caracteres de consulta que tem as características de uma pergunta. A resposta gerada é extraída literalmente do seu conteúdo, portanto, não incluirá conteúdo composto como o que você pode esperar de um modelo de conclusão de chat. Se a resposta semântica não for útil para seu cenário, você poderá omitir semantic_answers de seu código.

Para produzir uma resposta semântica, a pergunta e a resposta devem estar alinhadas de perto e o modelo deve encontrar conteúdo que responda claramente à pergunta. Se as respostas potenciais não atenderem a um limite de confiança, o modelo não retornará uma resposta. Para fins de demonstração, a pergunta neste exemplo foi projetada para obter uma resposta para que você possa ver a sintaxe.

  1. Crie um arquivo em ./src chamadosemanticAnswer.ts e copie o código a seguir para obter respostas semânticas.

    import { SearchClient } from "@azure/search-documents";
    import { HotelDocument, credential, searchEndpoint, indexName, semanticConfigurationName } from "./config.js";
    
    const searchClient = new SearchClient<HotelDocument>(
        searchEndpoint,
        indexName,
        credential
    );
    
    const results = await searchClient.search("What's a good hotel for people who like to read", {
        queryType: "semantic",
        semanticSearchOptions: {
            configurationName: semanticConfigurationName,
            captions: {
                captionType: "extractive"
            },
            answers: {
                answerType: "extractive"
            }
        },
        select: ["HotelName", "Description", "Category"]
    });
    
    console.log(`Answers:\n\n`);
    let rowNumber = 1; 
    
    // Extract semantic answers from the search results
    const semanticAnswers = results.answers;
    for (const answer of semanticAnswers || []) {
        console.log(`Semantic answer result #${rowNumber++}:`);
        if (answer.highlights) {
            console.log(`Semantic Answer: ${answer.highlights}`);
        } else {
            console.log(`Semantic Answer: ${answer.text}`);
        }
        console.log(`Semantic Answer Score: ${answer.score}\n\n`);
    }
    
    console.log(`Search Results:\n\n`);
    rowNumber = 1;
    
    // Iterate through the search results
    for await (const result of results.results) {
    
    
        // Log each result
        const doc = result.document;
        const rerankerScoreDisplay = result.rerankerScore;
        console.log(`Search result #${rowNumber++}:`);
        console.log(`${rerankerScoreDisplay}`);
        console.log(`${doc.HotelName}`);
        console.log(`${doc.Description || 'N/A'}`);
    
        const captions = result.captions;
    
        if (captions && captions.length > 0) {
            const caption = captions[0];
            if (caption.highlights) {
                console.log(`Caption: ${caption.highlights}\n`);
            } else {
                console.log(`Caption: ${caption.text}\n`);
            }
        }
    }
    
  2. Execute o código.

    npm run build && node -r dotenv/config dist/semanticAnswer.js
    
  3. A saída deve ser semelhante ao exemplo a seguir, em que a melhor resposta à pergunta é extraída de um dos resultados.

    Lembre-se de que as respostas são conteúdo verbatim extraído do índice e podem estar faltando frases que um usuário esperaria ver. Para obter respostas compostas geradas por um modelo de conclusão de chat, considere usar um padrão RAG ou recuperação agêntica.

    Semantic answer result #1:
    Semantic Answer: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
    Semantic Answer Score: 0.9829999804496765
    

Limpar os recursos

Quando você está trabalhando em sua própria assinatura, é uma boa ideia identificar, no final de um projeto, se você ainda precisa dos recursos criados. Recursos deixados em execução podem custar dinheiro. Você pode excluir os recursos individualmente ou excluir o grupo de recursos para excluir todo o conjunto de recursos.

Você pode encontrar e gerenciar de recursos no portal do Azure usando o link Todos os recursos ouGrupos de recursos no painel de navegação à esquerda.

Neste início rápido, você aprendeu a invocar a classificação semântica em um índice existente. Recomendamos tentar a classificação semântica em seus próprios índices como uma próxima etapa. Os artigos a seguir podem ajudá-lo a começar.