Поделиться через


Быстрый старт: Семантическое ранжирование

Из этого краткого руководства вы узнаете, как добавить семантическое ранжирование в существующий индекс. Вы можете использовать индекс hotels-sample-index или ваш собственный.

В службе "Поиск искусственного интеллекта Azure" семантическая ранжирование — это функции на стороне запроса, которые используют понимание машинного чтения от Корпорации Майкрософт к результатам поиска rescore, повышая наиболее семантические совпадения в верхней части списка. В зависимости от содержимого и запроса семантический рейтинг может значительно повысить релевантность поиска с минимальными усилиями разработчика.

Вы можете добавить семантическую конфигурацию в существующий индекс без необходимости перестройки. Семантическая ранжирование наиболее эффективна для текста, который является информационным или описательным.

Из этого краткого руководства вы узнаете, как:

  • Добавление семантической конфигурации в индекс поиска
  • Добавление семантических параметров в запрос

Необходимые компоненты

Настройка доступа

Вы можете подключиться к службе поиска ИИ Azure с помощью ключей API или идентификатора Microsoft Entra с назначениями ролей. Ключи проще начать с, но роли более безопасны.

Чтобы настроить доступ на основе ролей, выполните приведенные действия.

  1. Войдите на портал Azure и выберите службу поиска.

  2. На левой панели выберите Настройки>Ключи.

  3. В разделе "Управление доступом к API" выберите "Оба".

    Этот параметр включает проверку подлинности на основе ключей и без ключа. После назначения ролей вы можете вернуться к этому шагу и выбрать управление доступом на основе ролей.

  4. В левой области выберите элемент управления доступом (IAM).

  5. Выберите Добавить>Добавить назначение ролей.

  6. Назначьте эти роли учетной записи пользователя:

    • Участник службы поиска

    • Участник данных индекса поиска

Дополнительные сведения см. в статье "Подключение к поиску ИИ Azure" с помощью ролей.

Начните с индекса

В этом кратком руководстве предполагается, что уже существует индекс, который был изменен для включения семантической конфигурации. Мы рекомендуем использовать индекс hotels-sample-index, который можно создать за считанные минуты средствами мастера Azure-портала.

  1. Войдите в портал Azure и найдите службу поиска.

  2. В разделе"Индексы управления >поиском" откройте индекс hotels-sample-index. Убедитесь, что индекс не имеет семантической конфигурации.

    Снимок экрана: пустая страница семантической конфигурации на портале Azure.

  3. Чтобы проверить, работает ли индекс, выполните запрос. В обозревателе поиска введите эту строку поиска "ходьба к живой музыке" , чтобы просмотреть ответ перед применением семантического ранжирования.

    Снимок экрана: запрос в обозревателе поиска на портале.

    Ответ должен быть похож на следующий пример, оцениваемый по умолчанию ранжировщиком BM25 L1 для полнотекстового поиска. Для удобства чтения в примере выбираются только поля "HotelName" "HotelId" и "Description".

    Этот запрос — это поиск ключевых слов. Совпадения содержат дословные совпадения с терминами запроса (ходьба, расстояние, живая музыка) или лингвистические варианты одного из терминов (ходьбы, жизнь).

    "@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."
      }
    ]
    

Позже этот запрос можно попробовать еще раз после настройки семантического ранжирования, чтобы узнать, как изменяется ответ.

Подсказка

Вы можете добавить семантическую конфигурацию на портале Azure. Однако если вы хотите узнать, как добавить семантику конфигурации программным способом, перейдите к инструкциям в этом кратком руководстве.

Настройка клиента

В этом кратком руководстве вы используете интегрированную среду разработки и клиентскую библиотеку Azure.Search.Documents для добавления семантического ранжирования в существующий индекс поиска.

Мы рекомендуем Visual Studio для этого быстрого начала.

Подсказка

Исходный код можно скачать, чтобы начать с готового проекта или выполнить следующие действия, чтобы создать собственный.

Установка библиотек

  1. Запустите Visual Studio и откройте quickstart-semantic-search.sln или создайте проект с помощью шаблона консольного приложения.

  2. В разделе Инструменты>Диспетчер пакетов NuGet выберите Управление пакетами NugGet для решения....

  3. Выберите Обзор.

  4. Найдите пакет Azure.Search.Documents и выберите последнюю стабильную версию.

  5. Найдите пакет Azure.Identity и выберите последнюю стабильную версию.

  6. Выберите " Установить" , чтобы добавить сборку в проект и решение.

Вход в Azure

Если вы вошли на портал Azure, вы вошли в Azure. Если вы не уверены, используйте Azure CLI или Azure PowerShell для входа в систему: az login или az connect. Если у вас несколько арендаторов и подписок, см. Краткое руководство: Подключение без ключей для получения помощи по подключению.

Обновление индекса

В этом разделе вы обновите индекс поиска, чтобы включить семантическую конфигурацию. Код получает определение индекса из службы поиска и добавляет семантическую конфигурацию.

  1. Откройте проект BuildIndex в Visual Studio. Программа состоит из следующего кода.

    Этот код использует SearchIndexClient для обновления индекса в службе поиска.

    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. Замените URL-адрес службы поиска допустимой конечной точкой.

  3. Запустите программу.

  4. Выходные данные записываются в окно консоли из Console.WriteLine. Для каждого шага должны отображаться сообщения, включая JSON схемы индекса с новой семантической конфигурацией.

Выполнение семантических запросов

В этом разделе программа выполняет несколько семантических запросов в последовательности.

  1. Откройте проект QueryIndex в Visual Studio. Программа состоит из следующего кода.

    Этот код использует SearchClient для отправки запросов в индекс.

    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. Замените URL-адрес службы поиска допустимой конечной точкой.

  3. Запустите программу.

  4. Выходные данные записываются в окно консоли из Console.WriteLine. Результаты поиска должны отображаться для каждого запроса.

Выходные данные для семантического запроса (без подписей или ответов)

Это выходные данные из семантического запроса без подписей или ответов. Строка запроса — "пешая доступность до живой музыки".

Здесь начальные результаты терминного запроса пересматриваются с использованием семантических моделей ранжирования. Для этого конкретного набора данных и запроса первые несколько результатов находятся в аналогичных позициях. Эффекты семантического ранжирования более выражены в оставшейся части результатов.

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...

Выходные данные для семантического запроса с заголовками

Этот запрос добавляет заголовки с выделением попаданий.

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...

Выходные данные для семантических ответов

В этом окончательном запросе возвращаются семантические ответы. Обратите внимание, что мы изменили строку запроса для этого примера: "Что такое хороший отель для людей, которые любят читать".

Семантический рангировщик может создать ответ на строку запроса, которая имеет характеристики вопроса. Созданный ответ извлекается непосредственно из вашего содержимого, поэтому он не будет содержать составленного контента, который можно ожидать от модели завершения чата. Если семантический ответ не полезен для вашего сценария, можно исключить semantic_answers из вашего кода.

Чтобы получить семантический ответ, вопрос и ответ должны быть тесно согласованы, и модель должна найти содержимое, которое четко отвечает на этот вопрос. Если потенциальные ответы не соответствуют порогу достоверности, модель не возвращает ответ. В демонстрационных целях вопрос в этом примере предназначен для получения ответа, чтобы увидеть синтаксис.

Помните, что ответы являются дословным содержимым, полученным из индекса, и могут отсутствовать фразы, которые пользователь может ожидать увидеть. Чтобы получить составленные ответы, созданные моделью завершения чата, рассмотрите использование шаблона RAG или агентного извлечения.

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
----------------------------------------

Из этого краткого руководства вы узнаете, как добавить семантическое ранжирование в существующий индекс. Вы можете использовать индекс hotels-sample-index или ваш собственный.

В службе "Поиск искусственного интеллекта Azure" семантическая ранжирование — это функции на стороне запроса, которые используют понимание машинного чтения от Корпорации Майкрософт к результатам поиска rescore, повышая наиболее семантические совпадения в верхней части списка. В зависимости от содержимого и запроса семантический рейтинг может значительно повысить релевантность поиска с минимальными усилиями разработчика.

Вы можете добавить семантическую конфигурацию в существующий индекс без необходимости перестройки. Семантическая ранжирование наиболее эффективна для текста, который является информационным или описательным.

Из этого краткого руководства вы узнаете, как:

  • Добавление семантической конфигурации в индекс поиска
  • Добавление семантических параметров в запрос

Необходимые компоненты

Настройка доступа

Вы можете подключиться к службе поиска ИИ Azure с помощью ключей API или идентификатора Microsoft Entra с назначениями ролей. Ключи проще начать с, но роли более безопасны.

Чтобы настроить доступ на основе ролей, выполните приведенные действия.

  1. Войдите на портал Azure и выберите службу поиска.

  2. На левой панели выберите Настройки>Ключи.

  3. В разделе "Управление доступом к API" выберите "Оба".

    Этот параметр включает проверку подлинности на основе ключей и без ключа. После назначения ролей вы можете вернуться к этому шагу и выбрать управление доступом на основе ролей.

  4. В левой области выберите элемент управления доступом (IAM).

  5. Выберите Добавить>Добавить назначение ролей.

  6. Назначьте эти роли учетной записи пользователя:

    • Участник службы поиска

    • Участник данных индекса поиска

Дополнительные сведения см. в статье "Подключение к поиску ИИ Azure" с помощью ролей.

Начните с индекса

В этом кратком руководстве предполагается, что уже существует индекс, который был изменен для включения семантической конфигурации. Мы рекомендуем использовать индекс hotels-sample-index, который можно создать за считанные минуты средствами мастера Azure-портала.

  1. Войдите в портал Azure и найдите службу поиска.

  2. В разделе"Индексы управления >поиском" откройте индекс hotels-sample-index. Убедитесь, что индекс не имеет семантической конфигурации.

    Снимок экрана: пустая страница семантической конфигурации на портале Azure.

  3. Чтобы проверить, работает ли индекс, выполните запрос. В обозревателе поиска введите эту строку поиска "ходьба к живой музыке" , чтобы просмотреть ответ перед применением семантического ранжирования.

    Снимок экрана: запрос в обозревателе поиска на портале.

    Ответ должен быть похож на следующий пример, оцениваемый по умолчанию ранжировщиком BM25 L1 для полнотекстового поиска. Для удобства чтения в примере выбираются только поля "HotelName" "HotelId" и "Description".

    Этот запрос — это поиск ключевых слов. Совпадения содержат дословные совпадения с терминами запроса (ходьба, расстояние, живая музыка) или лингвистические варианты одного из терминов (ходьбы, жизнь).

    "@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."
      }
    ]
    

Позже этот запрос можно попробовать еще раз после настройки семантического ранжирования, чтобы узнать, как изменяется ответ.

Подсказка

Вы можете добавить семантическую конфигурацию на портале Azure. Однако если вы хотите узнать, как добавить семантику конфигурации программным способом, перейдите к инструкциям в этом кратком руководстве.

Настройка клиента

В этом кратком руководстве используйте записную книжку Jupyter и библиотеку azure-search-documents в пакете SDK Azure для Python, чтобы узнать о семантической ранжировке.

Мы рекомендуем Visual Studio Code с Python 3.10 или более поздней версии и расширение Python для этого быстрого старта.

Подсказка

Вы можете скачать завершенную записную книжку , чтобы начать работу с готовым проектом или выполнить следующие действия, чтобы создать собственную.

Для этого краткого руководства рекомендуется использовать виртуальную среду:

  1. Запустите Visual Studio Code.

  2. Откройте файл semantic-search-quickstart.ipynb или создайте новый ноутбук.

  3. Откройте палитру команд с помощью клавиш CTRL+SHIFT+P.

  4. Поиск Python : создание среды.

  5. Выберите Venv.

  6. Выбор интерпретатора Python Выберите 3.10 или более поздней версии.

Для настройки может потребоваться несколько минут. Если возникнут проблемы, ознакомьтесь со средами Python в VS Code.

Установка пакетов и установка переменных среды

  1. Установите пакеты, включая документы azure-search-documents.

    ! pip install -r requirements.txt --quiet
    
  2. .envПереименуйте в sample.env и укажите конечную точку службы поиска. Конечную точку можно получить на портале Azure на странице обзора службы поиска.

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

Вход в Azure

Если вы вошли на портал Azure, вы вошли в Azure. Если вы не уверены, используйте Azure CLI или Azure PowerShell для входа в систему: az login или az connect. Если у вас несколько арендаторов и подписок, см. Краткое руководство: Подключение без ключей для получения помощи по подключению.

Обновление индекса

В этом разделе вы обновите индекс поиска, чтобы включить семантическую конфигурацию. Код получает определение индекса из службы поиска и добавляет семантическую конфигурацию.

  1. Откройте файл semantic-search-quickstart.ipynb в Visual Studio Code или создайте новый файл.

  2. Укажите переменные, используемые в решении.

    # 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. Создайте SearchIndexClient и получите существующий индекс с именем "hotels-sample-index".

    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. Выполните код.

  5. Выходные данные — это имя индекса, списка полей и оператор, указывающий, существует ли семантическая конфигурация. В целях этого краткого руководства сообщение должно содержать: "Для этого индекса не существует семантической конфигурации".

  6. Добавьте семантическую конфигурацию в существующий индекс hotels-sample-index вашей поисковой службы. После добавления конфигурации поисковые документы не удаляются этой операцией, и индекс по-прежнему работает.

    # 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. Выполните код.

  8. Выходные данные — это только что добавленная семантическая конфигурация.

Выполнение семантических запросов

После того как индекс имеет семантику конфигурации, можно выполнять запросы, включающие семантические параметры.

  1. Создайте SearchClient и запрос, включающий тип семантического запроса и семантическую конфигурацию. Это минимальное требование для вызова семантического ранжирования.

    # 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. Выполните код.

  3. Выходные данные должны состоять из 13 документов, упорядоченных по "@search.reranker_score".

Возвращаемые субтитры

"При необходимости можно добавить подписи, чтобы извлечь части текста и применить выделение к важным терминам и фразам." Этот запрос добавляет заголовки.

  1. Добавьте captions в запрос.

    # 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. Выполните код.

  3. Выходные данные должны содержать новый элемент заголовка вместе с полем поиска. Подписи — это наиболее релевантные отрывки в результатах поиска. Если индекс содержит более крупные фрагменты текста, подпись полезна для извлечения наиболее интересных предложений.

    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.
    

Возврат семантических ответов

В этом окончательном запросе возвращаются семантические ответы.

Семантический рангировщик может создать ответ на строку запроса, которая имеет характеристики вопроса. Созданный ответ извлекается непосредственно из вашего содержимого, поэтому он не будет содержать составленного контента, который можно ожидать от модели завершения чата. Если семантический ответ не полезен для вашего сценария, можно исключить semantic_answers из вашего кода.

Чтобы получить семантический ответ, вопрос и ответ должны быть тесно согласованы, и модель должна найти содержимое, которое четко отвечает на этот вопрос. Если потенциальные ответы не соответствуют порогу достоверности, модель не возвращает ответ. В демонстрационных целях вопрос в этом примере предназначен для получения ответа, чтобы увидеть синтаксис.

  1. Добавьте answers в запрос.

    # 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. Выполните код.

  3. Выходные данные должны выглядеть примерно так, как показано в следующем примере, где лучший ответ на вопрос извлекается из одного из результатов.

    Помните, что ответы являются дословным содержимым, полученным из индекса, и могут отсутствовать фразы, которые пользователь может ожидать увидеть. Чтобы получить составленные ответы, созданные моделью завершения чата, рассмотрите использование шаблона RAG или агентного извлечения.

    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.
    
    ...
    

Из этого краткого руководства вы узнаете, как добавить семантическое ранжирование в существующий индекс. Вы можете использовать индекс hotels-sample-index или ваш собственный.

В службе "Поиск искусственного интеллекта Azure" семантическая ранжирование — это функции на стороне запроса, которые используют понимание машинного чтения от Корпорации Майкрософт к результатам поиска rescore, повышая наиболее семантические совпадения в верхней части списка. В зависимости от содержимого и запроса семантический рейтинг может значительно повысить релевантность поиска с минимальными усилиями разработчика.

Вы можете добавить семантическую конфигурацию в существующий индекс без необходимости перестройки. Семантическая ранжирование наиболее эффективна для текста, который является информационным или описательным.

Из этого краткого руководства вы узнаете, как:

  • Добавление семантической конфигурации в индекс поиска
  • Добавление семантических параметров в запрос

Необходимые компоненты

Настройка доступа

Вы можете подключиться к службе поиска ИИ Azure с помощью ключей API или идентификатора Microsoft Entra с назначениями ролей. Ключи проще начать с, но роли более безопасны.

Чтобы настроить доступ на основе ролей, выполните приведенные действия.

  1. Войдите на портал Azure и выберите службу поиска.

  2. На левой панели выберите Настройки>Ключи.

  3. В разделе "Управление доступом к API" выберите "Оба".

    Этот параметр включает проверку подлинности на основе ключей и без ключа. После назначения ролей вы можете вернуться к этому шагу и выбрать управление доступом на основе ролей.

  4. В левой области выберите элемент управления доступом (IAM).

  5. Выберите Добавить>Добавить назначение ролей.

  6. Назначьте эти роли учетной записи пользователя:

    • Участник службы поиска

    • Участник данных индекса поиска

Дополнительные сведения см. в статье "Подключение к поиску ИИ Azure" с помощью ролей.

Начните с индекса

В этом кратком руководстве предполагается, что уже существует индекс, который был изменен для включения семантической конфигурации. Мы рекомендуем использовать индекс hotels-sample-index, который можно создать за считанные минуты средствами мастера Azure-портала.

  1. Войдите в портал Azure и найдите службу поиска.

  2. В разделе"Индексы управления >поиском" откройте индекс hotels-sample-index. Убедитесь, что индекс не имеет семантической конфигурации.

    Снимок экрана: пустая страница семантической конфигурации на портале Azure.

  3. Чтобы проверить, работает ли индекс, выполните запрос. В обозревателе поиска введите эту строку поиска "ходьба к живой музыке" , чтобы просмотреть ответ перед применением семантического ранжирования.

    Снимок экрана: запрос в обозревателе поиска на портале.

    Ответ должен быть похож на следующий пример, оцениваемый по умолчанию ранжировщиком BM25 L1 для полнотекстового поиска. Для удобства чтения в примере выбираются только поля "HotelName" "HotelId" и "Description".

    Этот запрос — это поиск ключевых слов. Совпадения содержат дословные совпадения с терминами запроса (ходьба, расстояние, живая музыка) или лингвистические варианты одного из терминов (ходьбы, жизнь).

    "@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."
      }
    ]
    

Позже этот запрос можно попробовать еще раз после настройки семантического ранжирования, чтобы узнать, как изменяется ответ.

Подсказка

Вы можете добавить семантическую конфигурацию на портале Azure. Однако если вы хотите узнать, как добавить семантику конфигурации программным способом, перейдите к инструкциям в этом кратком руководстве.

Настройка клиента

В этом кратком руководстве вы используете клиент REST и REST API Azure AI Search для настройки и использования семантического ранжировщика.

Для этого краткого руководства мы рекомендуем использовать Visual Studio Code с расширением для клиента REST.

Подсказка

Исходный код можно скачать, чтобы начать с готового проекта или выполнить следующие действия, чтобы создать собственный.

  1. Запустите Visual Studio Code и откройте файл semantic-search-index-update.rest или создайте новый файл.

  2. В верхней части задайте переменные среды для службы поиска, авторизации и имени индекса.

    • Для @searchURLвойдите на портал Azure и скопируйте URL-адрес со страницы Обзор службы поиска.

    • Для @personalAccessToken следуйте инструкциям в Подключение без ключей, чтобы получить личный токен доступа.

  3. Чтобы проверить подключение, отправьте первый запрос.

    ### List existing indexes by name (verify the connection)
     GET  {{searchUrl}}/indexes?api-version=2025-05-01-preview&$select=name  HTTP/1.1
     Authorization: Bearer {{personalAccessToken}}
    
  4. Выберите "Отправленный запрос".

    Снимок экрана ссылки отправки запроса клиента REST.

  5. Выходные данные для этого запроса GET возвращают список существующих индексов. Вы должны получить код состояния успешного выполнения HTTP 200 и список индексов, включая индекс hotels-sample-index, используемый в этом кратком руководстве.

Обновление индекса

Чтобы обновить индекс с помощью REST API, необходимо предоставить всю схему, а также изменения, которые необходимо внести. Этот запрос предоставляет схему индекса hotels-sample-index, а также семантическую конфигурацию. Изменение состоит из следующего массива JSON.

"semantic": {
   "configurations": [
   {
      "name": "semantic-config",
      "flightingOptIn": false,
      "rankingOrder": "BoostedRerankerScore",
      "prioritizedFields": {
         "titleField": { "fieldName": "HotelName" },
         "prioritizedContentFields": [{ "fieldName": "Description" }],
         "prioritizedKeywordsFields": [{ "fieldName": "Tags" }]
      }
   }
   ]
}
  1. Сформулируйте запрос POST, указывающий имя индекса, операцию и полную схему JSON. Все необходимые элементы схемы должны присутствовать. Этот запрос включает полную схему для "hotels-sample-index" и семантическую конфигурацию.

    POST  {{searchUrl}}/indexes?api-version=2025-05-01-preview  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": [
        {
          "name": "sg",
          "searchMode": "analyzingInfixMatching",
          "sourceFields": ["Address/City", "Address/Country", "Rooms/Type", "Rooms/Tags"]
        }
      ],
      "analyzers": [],
      "normalizers": [],
      "tokenizers": [],
      "tokenFilters": [],
      "charFilters": [],
      "similarity": {
        "@odata.type": "#Microsoft.Azure.Search.BM25Similarity"
      },
      "semantic": {
        "configurations": [
          {
            "name": "semantic-config",
            "flightingOptIn": false,
            "rankingOrder": "BoostedRerankerScore",
            "prioritizedFields": {
              "titleField": {
                "fieldName": "HotelName"
              },
              "prioritizedContentFields": [
                {
                  "fieldName": "Description"
                }
              ],
              "prioritizedKeywordsFields": [
                {
                  "fieldName": "Tags"
                }
              ]
            }
          }
        ]
      }
    }
    
  2. Выберите "Отправленный запрос".

  3. Выходные данные для этого запроса POST — это сообщение о состоянии успешного выполнения HTTP 200.

Выполнение семантических запросов

Обязательные семантические параметры включают query_type и semantic_configuration_name. Ниже приведен пример базового семантического запроса с использованием минимальных параметров.

  1. Откройте файл semantic-search-query.rest или создайте новый файл.

  2. В верхней части файла задайте переменные среды для службы поиска, авторизации и имени индекса.

    • Для входа на портал Azure и копирования URL-адреса перейдите на страницу Обзор службы поиска.

    • Для @personalAccessToken этого следуйте инструкциям в Подключение без ключей, чтобы получить личный токен доступа.

  3. Проверьте подключение с помощью GET-запроса, который возвращает индекс "hotels-sample-index".

    GET  {{searchUrl}}/indexes/hotels-sample-index?api-version=2025-05-01-preview  HTTP/1.1
    Authorization: Bearer {{personalAccessToken}}
    
  4. Отправьте запрос, включающий тип семантического запроса и имя конфигурации.

     POST {{searchUrl}}/indexes/hotels-sample-index/docs/search?api-version=2025-05-01-preview  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. Выходные данные состоят из результатов поиска JSON. Тринадцать отелей соответствуют запросу. В этом примере включены первые семь.

    {
       "@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."
         }
       ]
     }
    

Возвращаемые субтитры

"При необходимости можно добавить подписи, чтобы извлечь части текста и применить выделение к важным терминам и фразам." Этот запрос добавляет заголовки, включающие выделение попаданий.

  1. captions Добавьте параметр и отправьте запрос.

    POST {{searchUrl}}/indexes/hotels-sample-index/docs/search?api-version=2025-05-01-preview  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. Выходные данные состоят из одинаковых результатов с добавлением "@search.captions". Ниже приведен код JSON для одного документа. Каждое совпадение включает оценки поиска, подписи в виде обычного текста, форматирование выделения и выбранные поля.

    {
       "@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."
    }
    

Возврат семантических ответов

В этом окончательном запросе возвращаются семантические ответы.

Семантический рангировщик может создать ответ на строку запроса, которая имеет характеристики вопроса. Созданный ответ извлекается непосредственно из вашего содержимого, поэтому он не будет содержать составленного контента, который можно ожидать от модели завершения чата. Если семантический ответ не полезен для вашего сценария, можно исключить semantic_answers из вашего кода.

Чтобы получить семантический ответ, вопрос и ответ должны быть тесно согласованы, и модель должна найти содержимое, которое четко отвечает на этот вопрос. Если потенциальные ответы не соответствуют порогу достоверности, модель не возвращает ответ. В демонстрационных целях вопрос в этом примере предназначен для получения ответа, чтобы увидеть синтаксис.

  1. Сформулируйте запрос с помощью строки поиска, которая задает вопрос.

    POST {{searchUrl}}/indexes/hotels-sample-index/docs/search?api-version=2025-05-01-preview  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. Результаты включают 41 ответ для нового запроса с "@search.answers" на вопрос об отелях для людей, которые любят читать.

    Помните, что ответы являются дословным содержимым, полученным из индекса, и могут отсутствовать фразы, которые пользователь может ожидать увидеть. Чтобы получить составленные ответы, созданные моделью завершения чата, рассмотрите использование шаблона RAG или агентного извлечения.

    В этом примере ответ признается как хорошее соответствие для вопроса.

    {
      "@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."
        }
      ]
    }
    

Очистка ресурсов

Если вы работаете в собственной подписке, в конце проекта следует решить, нужны ли вам созданные ресурсы. Ресурсы, которые продолжат работать, могут быть платными. Вы можете удалить ресурсы по отдельности либо удалить всю группу ресурсов.

Ресурсы и управление ими можно найти в портал Azure, используя ссылку "Все ресурсы" или "Группы ресурсов" в области навигации слева.

В этом кратком руководстве вы узнали, как вызвать семантический ранжирование по существующему индексу. Мы рекомендуем попробовать семантический ранжирование по собственным индексам в качестве следующего шага. Следующие статьи помогут вам приступить к работе.