共用方式為


快速入門:語意排名

在這個快速入門中,你將學習如何使用 語意排序 ,方法是在搜尋索引中加入語意配置,並在查詢中加入語意參數。 您可以使用 hotels-sample-index 或您自己的其中一個。

在 Azure AI Search 中,語意排名是查詢端功能,利用 Microsoft 的機器閱讀理解來重新評分搜尋結果,將語義相關的匹配推至列表頂端。 視內容和查詢而定,語意排名可以 大幅改善搜尋相關性 ,只需最少的開發人員工作。

您可以將語意組態新增至現有的索引,而不需要重建。 語意排名對可參考或描述性的文字最為有效。

先決條件

設定存取權

您可以使用 API 金鑰連線到 Azure AI 搜尋服務,或透過具備角色指派功能的 Microsoft Entra ID 進行連線。 金鑰較容易上手,但角色更安全。 如需詳細資訊,請參閱使用角色連線到 Azure AI 搜尋服務

若要設定角色型存取:

  1. 登入 Azure 入口網站 ,然後選取您的搜尋服務。

  2. 從左窗格中,選取 [設定]>[金鑰]

  3. API 存取控制中,選擇 以角色為基礎的存取控制,或選擇 兩者皆選,如果需要時間將客戶端轉換到角色為基礎的存取。

  4. 從左窗格中,選取 [訪問控制][IAM]。

  5. 選取 新增>新增角色指派

  6. 搜尋服務參與者搜尋索引數據參與者 角色指派給您的用戶帳戶。

從索引開始

此快速入門假設已有索引,並修改以包含語意配置。 我們建議您使用 Azure 入口網站精靈工具,您可以在幾分鐘內建立 hotels-sample-index

先從現有的指數開始:

  1. 登入 Azure 入口網站,然後尋找您的搜尋服務。

  2. 搜尋管理>索引中,選擇 hotels-sample-index。

  3. 選擇語義配置,確保索引未設置語義配置。

    Azure 入口網站中空語意設定頁面的螢幕快照。

  4. 選擇 搜尋總管,然後選擇 JSON 檢視

  5. 將以下 JSON 貼到查詢編輯器中。

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

    入口網站的搜尋總管中查詢的螢幕擷取畫面。

  6. 選取 [搜尋] 以執行查詢。

    此查詢是關鍵詞搜尋。 回應應與以下範例相似,該範例的結果如同經由用於全文檢索搜尋的預設 BM25 L1 排名工具所評分的結果。

    為了可讀性,範例僅選取 HotelIdHotelNameDescription 欄位。 結果包含查詢詞(walkingdistancelivemusic, ) 的逐字匹配,或語言變體(walkliving, )。

    "@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 入口網站中新增語意設定。 不過,如果你想學習如何用程式方式新增語意設定,請繼續這個快速入門。

設定用戶端

在本快速入門中,您會使用 IDE 和 Azure.Search.Documents 用戶端連結庫,將語意排名新增至現有的搜尋索引。

我們建議使用 Visual Studio 進行本快速入門。

小提示

您可以下載 原始碼 以開始使用已完成的專案,或遵循下列步驟來建立您自己的專案。

安裝函式庫

  1. 啟動 Visual Studio 並開啟 quickstart-semantic-ranking.sln ,或使用控制台應用程式範本建立新專案。

  2. 在 [工具]>[NuGet 套件管理員] 中,選取 [管理解決方案的 NuGet 套件] 中。

  3. 選取 [瀏覽]。

  4. 搜尋 Azure.Search.Documents 套件,然後選取最新的穩定版本。

  5. 搜尋 Azure.Identity 套件 ,然後選取最新的穩定版本。

  6. 選取 [安裝] 以將組件新增到您的專案與解決方案。

登入 Azure

如果您登入 Azure 入口網站,您就會登入 Azure。 如果您不確定,請使用 Azure CLI 或 Azure PowerShell 來登入: az loginaz connect。 如果您有多個租用戶和訂用帳戶,請參閱 快速入門:在沒有密鑰的情況下連線 ,以取得如何連線的說明。

更新索引

在本節中,您會更新搜尋索引以包含語意設定。 程序代碼會從搜尋服務取得索引定義,並新增語意組態。

  1. 在 Visual Studio 中開啟 BuildIndex 專案 。 程式包含下列程序代碼。

    此程式代碼會使用 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. 在 Visual Studio 中開啟 QueryIndex 專案 。 程式包含下列程序代碼。

    此程式代碼會使用 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 記錄至主控台視窗。 您應該會看到每個查詢的搜尋結果。

語意查詢的輸出(沒有標題或答案)

此輸出來自語意查詢,沒有標題或答案。 查詢字串是 'walking distance to live music'。

在這裡,會使用語意排名模型來重新記錄詞彙查詢的初始結果。 針對這個特定的數據集和查詢,前幾個結果會位於類似的位置。 語意排名的效果在結果的其餘部分更為明顯。

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 AI Search 中,語意排名是查詢端功能,利用 Microsoft 的機器閱讀理解來重新評分搜尋結果,將語義相關的匹配推至列表頂端。 視內容和查詢而定,語意排名可以 大幅改善搜尋相關性 ,只需最少的開發人員工作。

您可以將語意組態新增至現有的索引,而不需要重建。 語意排名對可參考或描述性的文字最為有效。

先決條件

設定存取權

您可以使用 API 金鑰連線到 Azure AI 搜尋服務,或透過具備角色指派功能的 Microsoft Entra ID 進行連線。 金鑰較容易上手,但角色更安全。 如需詳細資訊,請參閱使用角色連線到 Azure AI 搜尋服務

若要設定角色型存取:

  1. 登入 Azure 入口網站 ,然後選取您的搜尋服務。

  2. 從左窗格中,選取 [設定]>[金鑰]

  3. API 存取控制中,選擇 以角色為基礎的存取控制,或選擇 兩者皆選,如果需要時間將客戶端轉換到角色為基礎的存取。

  4. 從左窗格中,選取 [訪問控制][IAM]。

  5. 選取 新增>新增角色指派

  6. 搜尋服務參與者搜尋索引數據參與者 角色指派給您的用戶帳戶。

從索引開始

此快速入門假設已有索引,並修改以包含語意配置。 我們建議您使用 Azure 入口網站精靈工具,您可以在幾分鐘內建立 hotels-sample-index

先從現有的指數開始:

  1. 登入 Azure 入口網站,然後尋找您的搜尋服務。

  2. 搜尋管理>索引中,選擇 hotels-sample-index。

  3. 選擇語義配置,確保索引未設置語義配置。

    Azure 入口網站中空語意設定頁面的螢幕快照。

  4. 選擇 搜尋總管,然後選擇 JSON 檢視

  5. 將以下 JSON 貼到查詢編輯器中。

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

    入口網站的搜尋總管中查詢的螢幕擷取畫面。

  6. 選取 [搜尋] 以執行查詢。

    此查詢是關鍵詞搜尋。 回應應與以下範例相似,該範例的結果如同經由用於全文檢索搜尋的預設 BM25 L1 排名工具所評分的結果。

    為了可讀性,範例僅選取 HotelIdHotelNameDescription 欄位。 結果包含查詢詞(walkingdistancelivemusic, ) 的逐字匹配,或語言變體(walkliving, )。

    "@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 入口網站中新增語意設定。 不過,如果你想學習如何用程式方式新增語意設定,請繼續這個快速入門。

設定用戶端

在本快速入門中,您會使用 IDE 和 @azure/search-documents 用戶端程式庫,將語意排名新增至現有搜尋索引。

此快速入門假設您的電腦上有下列項目:

小提示

您可以下載 原始碼 以開始使用已完成的專案,或遵循下列步驟來建立您自己的專案。

設定本機開發環境

  1. 在新的目錄中啟動 Visual Studio Code。

    mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart
    code .
    
  2. 在專案目錄中建立 ESM 模組的新套件。

    npm init -y
    npm pkg set type=module
    
  3. 安裝套件,包括 azure-search-documents

    npm install @azure/identity @azure/search-documents dotenv
    
  4. 建立 .env 並提供您的搜尋服務端點。 您可以從 Azure 入口網站的搜尋服務 概觀 頁面,取得端點。

    AZURE_SEARCH_ENDPOINT=YOUR-SEARCH-SERVICE-ENDPOINT
    AZURE_SEARCH_INDEX_NAME=hotels-sample-index
    SEMANTIC_CONFIGURATION_NAME=semantic-config
    
  5. 在您的專案目錄中建立 src 目錄。

    mkdir src
    

登入 Azure

如果您登入 Azure 入口網站,您就會登入 Azure。 如果您不確定,請使用 Azure CLI 或 Azure PowerShell 來登入: az loginaz connect。 如果您有多個租用戶和訂用帳戶,請參閱 快速入門:在沒有密鑰的情況下連線 ,以取得如何連線的說明。

建立通用驗證檔案

在名為 ./srcconfig.ts 中建立檔案以讀取 .env 檔案並保存環境變數和驗證認證。 複製到以下程式碼中;不要變更。 此檔案將由本快速入門中的所有其他檔案使用。

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`);

取得索引結構描述

在本節中,您會取得搜尋服務上現有 hotels-sample-index 索引的設定。

  1. 在名為 ./srcgetIndexSettings.js 中建立檔案,然後複製到以下程式碼中。

    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. 執行程式碼。

    node -r dotenv/config src/getIndexSettings.js
    
  3. 輸出是索引的名稱、字段清單,以及指出語意組態是否存在的語句。 基於本快速入門的目的,訊息應該顯示 No semantic configuration exists for this index

使用語意設定更新索引

  1. 在名為 ./srcupdateIndexSettings.js 中建立檔案,然後複製到以下程式碼中,將語意設定新增至搜尋服務上的現有 hotels-sample-index 索引。 這項作業不會刪除任何搜尋檔,而且您的索引在新增組態之後仍可運作。

    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. 執行程式碼。

    node -r dotenv/config src/updateIndexSettings.js
    
  3. 輸出是您剛才新增的語意設定,Semantic configuration updated successfully.

執行語意查詢

hotels-sample-index 索引具有語意設定之後,您可以執行包含語意參數的查詢。

  1. 在名為 ./srcsemanticQuery.js 中建立檔案,然後複製到以下程式碼中,建立索引的語意查詢。 這是啟用語義排名的最低需求。

    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. 執行程式碼。

    node -r dotenv/config src/semanticQuery.js
    
  3. 輸出應該由排序 rerankerScoreDisplay的 13 份文件組成。

返回字幕

您可以選擇性地新增標題以擷取部分文字,並將點擊醒目提示套用至重要的字詞和片語。 此查詢會新增標題。

  1. 在名為 ./srcsemanticQueryReturnCaptions.js 中建立檔案,然後複製到以下程式碼中,將輔助字幕新增至查詢。

    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. 執行程式碼。

    node -r dotenv/config src/semanticQueryReturnCaptions.js
    
  3. 輸出應該包含新的標題元素與搜尋欄位。 標題是結果中最相關的段落。 如果您的索引包含較大的文字區塊,標題有助於擷取最有趣的句子。

    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.
    

傳回語意答案

這最後一個查詢會傳回語意答案。

語意排名器可以產生具有問題特性的查詢字串答案。 產生的答案會從您的內容中逐字擷取,因此它不會包含撰寫的內容,例如您從聊天完成模型預期的內容。 如果語意答案不適用於您的案例,您可以從程式代碼中省略 semantic_answers

若要產生語意答案,問題與答案必須緊密對齊,而且模型必須尋找清楚回答問題的內容。 若潛在答案未達信賴等級閾值,模型不會傳回答案。 在此為了示範,範例的問題已經過設計,可取得回應,以供您檢視語法。

  1. 在名為 ./srcsemanticAnswer.js 中建立檔案,然後複製到以下程式碼中,取得語意答案。

    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. 執行程式碼。

    node -r dotenv/config src/semanticAnswer.js
    
  3. 輸出看起來應該類似下列範例,其中從其中一個結果提取問題的最佳答案。

    回想一下,答案為從您的索引中提取之逐字內容,因此,可能會缺少使用者預期看到的片語。 若要取得聊天完成模型所產生的 組成答案 ,請考慮使用 RAG模式代理程式擷取

    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
    

在這個快速入門中,你將學習如何使用 語意排序 ,方法是在搜尋索引中加入語意配置,並在查詢中加入語意參數。 您可以使用 hotels-sample-index 或您自己的其中一個。

在 Azure AI Search 中,語意排名是查詢端功能,利用 Microsoft 的機器閱讀理解來重新評分搜尋結果,將語義相關的匹配推至列表頂端。 視內容和查詢而定,語意排名可以 大幅改善搜尋相關性 ,只需最少的開發人員工作。

您可以將語意組態新增至現有的索引,而不需要重建。 語意排名對可參考或描述性的文字最為有效。

先決條件

設定存取權

您可以使用 API 金鑰連線到 Azure AI 搜尋服務,或透過具備角色指派功能的 Microsoft Entra ID 進行連線。 金鑰較容易上手,但角色更安全。 如需詳細資訊,請參閱使用角色連線到 Azure AI 搜尋服務

若要設定角色型存取:

  1. 登入 Azure 入口網站 ,然後選取您的搜尋服務。

  2. 從左窗格中,選取 [設定]>[金鑰]

  3. API 存取控制中,選擇 以角色為基礎的存取控制,或選擇 兩者皆選,如果需要時間將客戶端轉換到角色為基礎的存取。

  4. 從左窗格中,選取 [訪問控制][IAM]。

  5. 選取 新增>新增角色指派

  6. 搜尋服務參與者搜尋索引數據參與者 角色指派給您的用戶帳戶。

從索引開始

此快速入門假設已有索引,並修改以包含語意配置。 我們建議您使用 Azure 入口網站精靈工具,您可以在幾分鐘內建立 hotels-sample-index

先從現有的指數開始:

  1. 登入 Azure 入口網站,然後尋找您的搜尋服務。

  2. 搜尋管理>索引中,選擇 hotels-sample-index。

  3. 選擇語義配置,確保索引未設置語義配置。

    Azure 入口網站中空語意設定頁面的螢幕快照。

  4. 選擇 搜尋總管,然後選擇 JSON 檢視

  5. 將以下 JSON 貼到查詢編輯器中。

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

    入口網站的搜尋總管中查詢的螢幕擷取畫面。

  6. 選取 [搜尋] 以執行查詢。

    此查詢是關鍵詞搜尋。 回應應與以下範例相似,該範例的結果如同經由用於全文檢索搜尋的預設 BM25 L1 排名工具所評分的結果。

    為了可讀性,範例僅選取 HotelIdHotelNameDescription 欄位。 結果包含查詢詞(walkingdistancelivemusic, ) 的逐字匹配,或語言變體(walkliving, )。

    "@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 入口網站中新增語意設定。 不過,如果你想學習如何用程式方式新增語意設定,請繼續這個快速入門。

設定用戶端

在本快速入門中,您會使用 IDE 和 Azure AI 搜尋服務 Java SDK 用戶端程式庫,將語意排名新增至現有搜尋索引。

此快速入門假設您的電腦上有下列項目:

設定本機開發環境

  1. 建立新的 Maven 專案目錄。

    mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart
    code .
    
  2. 建立具有必要相依性的 pom.xml 檔案。

    <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. 編譯專案以解決相依關係。

    mvn compile
    
  4. 建立來源目錄結構。

    mkdir -p src/main/java/com/azure/search/quickstart
    mkdir -p src/main/resources
    
  5. application.properties目錄中建立src/main/resources檔案,並提供你的搜尋服務端點。 您可以從 Azure 入口網站的搜尋服務 概觀 頁面,取得端點。

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

登入 Azure

如果您登入 Azure 入口網站,您就會登入 Azure。 如果您不確定,請使用 Azure CLI 登入:az login。 如果您有多個租用戶和訂用帳戶,請參閱 快速入門:在沒有密鑰的情況下連線 ,以取得如何連線的說明。

建立通用設定類別

在目錄中建立 SearchConfig.java 一個檔案 src/main/java/com/azure/search/quickstart 來讀取屬性檔案,並存放設定值和認證憑證。

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");
    }
}

取得索引結構描述

在本節中,您會取得搜尋服務上現有 hotels-sample-index 索引的設定。

  1. GetIndexSettings.java 目錄中建立src/main/java/com/azure/search/quickstart檔案。

    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. 編譯並執行程式碼。

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.GetIndexSettings"
    
  3. 輸出是索引的名稱、字段清單,以及指出語意組態是否存在的語句。 基於本快速入門的目的,訊息應該顯示 No semantic configuration exists for this index

使用語意設定更新索引

  1. UpdateIndexSettings.java 目錄中建立 src/main/java/com/azure/search/quickstart 檔案,以向搜尋服務中現有 hotels-sample-index 的索引加入語義配置。

    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. 編譯並執行程式碼。

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.UpdateIndexSettings"
    
  3. 輸出是您剛才新增的語意設定,Semantic configuration updated successfully.

執行語意查詢

在索引hotels-sample-index經配置語意後,你可以執行包括語意參數的查詢。

  1. SemanticQuery.java 目錄中建立 src/main/java/com/azure/search/quickstart 檔案,以進行索引的語意查詢。

    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. 編譯並執行程式碼。

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticQuery"
    
  3. 輸出應包含 13 個文件,依重新排名器分數排序。

返回字幕

您可以選擇性地新增標題以擷取部分文字,並將點擊醒目提示套用至重要的字詞和片語。

  1. SemanticQueryWithCaptions.java 目錄中建立src/main/java/com/azure/search/quickstart檔案。

    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. 編譯並執行程式碼。

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticQueryWithCaptions"
    
  3. 輸出應該包含新的標題元素與搜尋欄位。 標題是結果中最相關的段落。 如果您的索引包含較大的文字區塊,標題有助於擷取最有趣的句子。

    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.
    

傳回語意答案

這最後一個查詢會傳回語意答案。

語意排名器可以產生具有問題特性的查詢字串答案。 產生的答案會從您的內容中逐字擷取,因此它不會包含撰寫的內容,例如您從聊天完成模型預期的內容。

若要產生語意答案,問題與答案必須緊密對齊,而且模型必須尋找清楚回答問題的內容。 若潛在答案未達信賴等級閾值,模型不會傳回答案。 在此為了示範,範例的問題已經過設計,可取得回應,以供您檢視語法。

  1. SemanticAnswer.java 目錄中建立src/main/java/com/azure/search/quickstart檔案。

    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. 編譯並執行程式碼。

    mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticAnswer"
    
  3. 輸出看起來應該類似下列範例,其中從其中一個結果提取問題的最佳答案。

    回想一下,答案為從您的索引中提取之逐字內容,因此,可能會缺少使用者預期看到的片語。 若要取得聊天完成模型所產生的 組成答案 ,請考慮使用 RAG模式代理程式擷取

    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
    

在這個快速入門中,你將學習如何使用 語意排序 ,方法是在搜尋索引中加入語意配置,並在查詢中加入語意參數。 您可以使用 hotels-sample-index 或您自己的其中一個。

在 Azure AI Search 中,語意排名是查詢端功能,利用 Microsoft 的機器閱讀理解來重新評分搜尋結果,將語義相關的匹配推至列表頂端。 視內容和查詢而定,語意排名可以 大幅改善搜尋相關性 ,只需最少的開發人員工作。

您可以將語意組態新增至現有的索引,而不需要重建。 語意排名對可參考或描述性的文字最為有效。

先決條件

設定存取權

您可以使用 API 金鑰連線到 Azure AI 搜尋服務,或透過具備角色指派功能的 Microsoft Entra ID 進行連線。 金鑰較容易上手,但角色更安全。 如需詳細資訊,請參閱使用角色連線到 Azure AI 搜尋服務

若要設定角色型存取:

  1. 登入 Azure 入口網站 ,然後選取您的搜尋服務。

  2. 從左窗格中,選取 [設定]>[金鑰]

  3. API 存取控制中,選擇 以角色為基礎的存取控制,或選擇 兩者皆選,如果需要時間將客戶端轉換到角色為基礎的存取。

  4. 從左窗格中,選取 [訪問控制][IAM]。

  5. 選取 新增>新增角色指派

  6. 搜尋服務參與者搜尋索引數據參與者 角色指派給您的用戶帳戶。

從索引開始

此快速入門假設已有索引,並修改以包含語意配置。 我們建議您使用 Azure 入口網站精靈工具,您可以在幾分鐘內建立 hotels-sample-index

先從現有的指數開始:

  1. 登入 Azure 入口網站,然後尋找您的搜尋服務。

  2. 搜尋管理>索引中,選擇 hotels-sample-index。

  3. 選擇語義配置,確保索引未設置語義配置。

    Azure 入口網站中空語意設定頁面的螢幕快照。

  4. 選擇 搜尋總管,然後選擇 JSON 檢視

  5. 將以下 JSON 貼到查詢編輯器中。

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

    入口網站的搜尋總管中查詢的螢幕擷取畫面。

  6. 選取 [搜尋] 以執行查詢。

    此查詢是關鍵詞搜尋。 回應應與以下範例相似,該範例的結果如同經由用於全文檢索搜尋的預設 BM25 L1 排名工具所評分的結果。

    為了可讀性,範例僅選取 HotelIdHotelNameDescription 欄位。 結果包含查詢詞(walkingdistancelivemusic, ) 的逐字匹配,或語言變體(walkliving, )。

    "@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 入口網站中新增語意設定。 不過,如果你想學習如何用程式方式新增語意設定,請繼續這個快速入門。

設定用戶端

在本快速入門中,使用 Python 的 Azure SDK 中的 Jupyter Notebook 和 azure-search-documents 程式庫來了解語意排名。

針對本快速入門,我們建議使用 Python 3.10 或更新版本的 Visual Studio CodePython 延伸模組

小提示

您可以 下載已完成的筆記本 ,以從已完成的項目開始,或遵循下列步驟來建立您自己的筆記本。

建議本快速入門的虛擬環境:

  1. 啟動 Visual Studio Code。

  2. 打開 semantic-ranking-quickstart.ipynb 檔案或建立一個新的筆記本。

  3. 使用 Ctrl+Shift+P 開啟命令選擇區。

  4. 搜尋 Python:建立環境

  5. 選取 Venv.

  6. 選取 Python 解譯器。 選擇 3.10 或更新版本。

設定可能需要一分鐘的時間。 如果您遇到問題,請參閱 VS Code 中的 Python 環境。

安裝套件並設定環境變數

  1. 安裝套件,包括 azure-search-documents

    ! pip install -r requirements.txt --quiet
    
  2. 將重新命名 sample.env.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 loginaz connect。 如果您有多個租用戶和訂用帳戶,請參閱 快速入門:在沒有密鑰的情況下連線 ,以取得如何連線的說明。

更新索引

在本節中,您會更新搜尋索引以包含語意設定。 程序代碼會從搜尋服務取得索引定義,並新增語意組態。

  1. 在 Visual Studio Code 中開啟 semantic-ranking-quickstart.ipynb 檔案,或建立新檔案。

  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. 輸出應該由排序 "@search.reranker_score"的 13 份文件組成。

返回字幕

您可以選擇性地新增標題以擷取部分文字,並將點擊醒目提示套用至重要的字詞和片語。 此查詢會新增標題。

  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 AI Search 中,語意排名是查詢端功能,利用 Microsoft 的機器閱讀理解來重新評分搜尋結果,將語義相關的匹配推至列表頂端。 視內容和查詢而定,語意排名可以 大幅改善搜尋相關性 ,只需最少的開發人員工作。

您可以將語意組態新增至現有的索引,而不需要重建。 語意排名對可參考或描述性的文字最為有效。

先決條件

設定存取權

您可以使用 API 金鑰連線到 Azure AI 搜尋服務,或透過具備角色指派功能的 Microsoft Entra ID 進行連線。 金鑰較容易上手,但角色更安全。 如需詳細資訊,請參閱使用角色連線到 Azure AI 搜尋服務

若要設定角色型存取:

  1. 登入 Azure 入口網站 ,然後選取您的搜尋服務。

  2. 從左窗格中,選取 [設定]>[金鑰]

  3. API 存取控制中,選擇 以角色為基礎的存取控制,或選擇 兩者皆選,如果需要時間將客戶端轉換到角色為基礎的存取。

  4. 從左窗格中,選取 [訪問控制][IAM]。

  5. 選取 新增>新增角色指派

  6. 搜尋服務參與者搜尋索引數據參與者 角色指派給您的用戶帳戶。

從索引開始

此快速入門假設已有索引,並修改以包含語意配置。 我們建議您使用 Azure 入口網站精靈工具,您可以在幾分鐘內建立 hotels-sample-index

先從現有的指數開始:

  1. 登入 Azure 入口網站,然後尋找您的搜尋服務。

  2. 搜尋管理>索引中,選擇 hotels-sample-index。

  3. 選擇語義配置,確保索引未設置語義配置。

    Azure 入口網站中空語意設定頁面的螢幕快照。

  4. 選擇 搜尋總管,然後選擇 JSON 檢視

  5. 將以下 JSON 貼到查詢編輯器中。

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

    入口網站的搜尋總管中查詢的螢幕擷取畫面。

  6. 選取 [搜尋] 以執行查詢。

    此查詢是關鍵詞搜尋。 回應應與以下範例相似,該範例的結果如同經由用於全文檢索搜尋的預設 BM25 L1 排名工具所評分的結果。

    為了可讀性,範例僅選取 HotelIdHotelNameDescription 欄位。 結果包含查詢詞(walkingdistancelivemusic, ) 的逐字匹配,或語言變體(walkliving, )。

    "@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 用戶端和 Azure AI 搜尋 REST API 來設定及使用語意排名器。

我們建議在 Visual Studio Code 上安裝 REST 客戶端擴充套件 來進行本快速入門。

小提示

您可以下載 原始碼 以開始使用已完成的專案,或遵循下列步驟來建立您自己的專案。

  1. 啟動 Visual Studio Code,開啟 semantic-index-update.rest 檔案或建立新檔案。

  2. 在頂端,設定搜尋服務、授權和索引名稱的環境變數。

    • 針對 @searchURL,請登入 Azure 入口網站,然後從搜尋服務概觀頁面複製 URL。

    • 針對 @personalAccessToken,請依照 無需密鑰連接中的指示以取得您的個人存取令牌。

  3. 若要測試連線,請傳送您的第一個要求。

    ### 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. 選擇 [傳送要求]

    REST 用戶端傳送要求連結的螢幕快照。

  5. 此 GET 要求的輸出會傳回現有索引的清單。 您應該會收到 HTTP 200 成功狀態碼和索引清單,包括本快速入門中使用的 hotels-sample-index。

更新索引

若要使用 REST API 更新索引,您必須提供整個架構,以及您想要所做的修改。 此要求提供 hotels-sample-index 架構,以及語意設定。 修改由以下的 JSON 組成。

"semantic": {
   "configurations": [
   {
      "name": "semantic-config",
      "rankingOrder": "BoostedRerankerScore",
      "prioritizedFields": {
         "titleField": { "fieldName": "HotelName" },
         "prioritizedContentFields": [{ "fieldName": "Description" }],
         "prioritizedKeywordsFields": [{ "fieldName": "Tags" }]
      }
   }
   ]
}
  1. 建立一個 PUT 請求,指定索引名稱、操作及完整 JSON 架構。 架構的所有必要元素都必須存在。 此要求包含 hotels-sample-index 和語意設定的完整架構。

    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. 選擇 [傳送要求]

  3. 此 POST 請求的輸出是 HTTP 200 Success 狀態訊息。

執行語意查詢

必要的語意參數包括 query_typesemantic_configuration_name。 以下是使用最低參數的基本語意查詢範例。

  1. 打開 semantic-query.rest 檔案或建立新檔案。

  2. 在檔案頂端,設定搜尋服務、授權和索引名稱的環境變數。

    • 針對 @searchURL,請登入 Azure 入口網站,然後從搜尋服務概觀頁面複製 URL。

    • 針對 @personalAccessToken,請依照 無需密鑰連接中的指示以取得您的個人存取令牌。

  3. 使用會傳回 hotels-sample-index 的 GET 要求來測試連線。

    GET {{searchUrl}}/indexes/hotels-sample-index?api-version=2025-09-01  HTTP/1.1
    Authorization: Bearer {{personalAccessToken}}
    
  4. 傳送包含語意查詢類型和組態名稱的查詢。

     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. 輸出包含 JSON 搜尋結果。 13 家酒店符合查詢。 此範例中包含前七名。

    {
       "@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-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. 輸出包含相同的結果,並新增 "@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-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. 輸出包含新查詢的 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."
        }
      ]
    }
    

在這個快速入門中,你將學習如何使用 語意排序 ,方法是在搜尋索引中加入語意配置,並在查詢中加入語意參數。 您可以使用 hotels-sample-index 或您自己的其中一個。

在 Azure AI Search 中,語意排名是查詢端功能,利用 Microsoft 的機器閱讀理解來重新評分搜尋結果,將語義相關的匹配推至列表頂端。 視內容和查詢而定,語意排名可以 大幅改善搜尋相關性 ,只需最少的開發人員工作。

您可以將語意組態新增至現有的索引,而不需要重建。 語意排名對可參考或描述性的文字最為有效。

先決條件

設定存取權

您可以使用 API 金鑰連線到 Azure AI 搜尋服務,或透過具備角色指派功能的 Microsoft Entra ID 進行連線。 金鑰較容易上手,但角色更安全。 如需詳細資訊,請參閱使用角色連線到 Azure AI 搜尋服務

若要設定角色型存取:

  1. 登入 Azure 入口網站 ,然後選取您的搜尋服務。

  2. 從左窗格中,選取 [設定]>[金鑰]

  3. API 存取控制中,選擇 以角色為基礎的存取控制,或選擇 兩者皆選,如果需要時間將客戶端轉換到角色為基礎的存取。

  4. 從左窗格中,選取 [訪問控制][IAM]。

  5. 選取 新增>新增角色指派

  6. 搜尋服務參與者搜尋索引數據參與者 角色指派給您的用戶帳戶。

從索引開始

此快速入門假設已有索引,並修改以包含語意配置。 我們建議您使用 Azure 入口網站精靈工具,您可以在幾分鐘內建立 hotels-sample-index

先從現有的指數開始:

  1. 登入 Azure 入口網站,然後尋找您的搜尋服務。

  2. 搜尋管理>索引中,選擇 hotels-sample-index。

  3. 選擇語義配置,確保索引未設置語義配置。

    Azure 入口網站中空語意設定頁面的螢幕快照。

  4. 選擇 搜尋總管,然後選擇 JSON 檢視

  5. 將以下 JSON 貼到查詢編輯器中。

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

    入口網站的搜尋總管中查詢的螢幕擷取畫面。

  6. 選取 [搜尋] 以執行查詢。

    此查詢是關鍵詞搜尋。 回應應與以下範例相似,該範例的結果如同經由用於全文檢索搜尋的預設 BM25 L1 排名工具所評分的結果。

    為了可讀性,範例僅選取 HotelIdHotelNameDescription 欄位。 結果包含查詢詞(walkingdistancelivemusic, ) 的逐字匹配,或語言變體(walkliving, )。

    "@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 入口網站中新增語意設定。 不過,如果你想學習如何用程式方式新增語意設定,請繼續這個快速入門。

設定用戶端

在本快速入門中,您會使用 IDE 和 @azure/search-documents 用戶端程式庫,將語意排名新增至現有搜尋索引。

此快速入門假設您的電腦上有下列項目:

小提示

您可以下載 原始碼 以開始使用已完成的專案,或遵循下列步驟來建立您自己的專案。

設定本機開發環境

  1. 在新的目錄中啟動 Visual Studio Code。

    mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart
    code .
    
  2. 在專案目錄中建立 ESM 模組的新套件。

    npm init -y
    npm pkg set type=module
    
  3. 安裝開發套件,包括 azure-search-documents

    npm install @azure/identity @azure/search-documents dotenv
    
  4. 安裝開發相依性套件。

    npm install dotenv @types/node --save-dev
    
  5. 在專案目錄中建立 tsconfig.json 檔案以啟用 ESM 模組並設定模組解析。

     {
       "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. 更新 package.json 以包含用於建置 TypeScript 檔案的指令碼。 在該 scripts 區段新增以下行。

    "build": "tsc"
    
  7. 建立 .env 並提供您的搜尋服務端點。 您可以從 Azure 入口網站的搜尋服務 概觀 頁面,取得端點。

    AZURE_SEARCH_ENDPOINT=YOUR-SEARCH-SERVICE-ENDPOINT
    AZURE_SEARCH_INDEX_NAME=hotels-sample-index
    SEMANTIC_CONFIGURATION_NAME=semantic-config
    
  8. 在您的專案目錄中建立 src 目錄。

    mkdir src
    

登入 Azure

如果您登入 Azure 入口網站,您就會登入 Azure。 如果您不確定,請使用 Azure CLI 或 Azure PowerShell 來登入: az loginaz connect。 如果您有多個租用戶和訂用帳戶,請參閱 快速入門:在沒有密鑰的情況下連線 ,以取得如何連線的說明。

建立通用驗證檔案

在名為 ./srcconfig.ts 中建立檔案以讀取 .env 檔案並保存環境變數和驗證認證。 複製到以下程式碼中;不要變更。 此檔案將由本快速入門中的所有其他檔案使用。

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

取得索引結構描述

在本節中,您會取得搜尋服務上現有 hotels-sample-index 索引的設定。

  1. 在名為 ./srcgetIndexSettings.ts 中建立檔案,然後複製到以下程式碼中。

    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. 執行程式碼。

    npm run build && node -r dotenv/config dist/getIndexSettings.js
    
  3. 輸出是索引的名稱、字段清單,以及指出語意組態是否存在的語句。 基於本快速入門的目的,訊息應該顯示 No semantic configuration exists for this index

使用語意設定更新索引

  1. 在名為 ./srcupdateIndexSettings.ts 中建立檔案,然後複製到以下程式碼中,將語意設定新增至搜尋服務上的現有 hotels-sample-index 索引。 這項作業不會刪除任何搜尋檔,而且您的索引在新增組態之後仍可運作。

    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. 執行程式碼。

    npm run build && node -r dotenv/config dist/updateIndexSettings.js
    
  3. 輸出是您剛才新增的語意設定,Semantic configuration updated successfully.

執行語意查詢

hotels-sample-index 索引具有語意設定之後,您可以執行包含語意參數的查詢。

  1. 在名為 ./srcsemanticQuery.ts 中建立檔案,然後複製到以下程式碼中,建立索引的語意查詢。 這是啟用語義排名的最低需求。

    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. 執行程式碼。

    npm run build && node -r dotenv/config dist/semanticQuery.js
    
  3. 輸出應該由排序 rerankerScoreDisplay的 13 份文件組成。

返回字幕

您可以選擇性地新增標題以擷取部分文字,並將點擊醒目提示套用至重要的字詞和片語。 此查詢會新增標題。

  1. 在名為 ./srcsemanticQueryReturnCaptions.ts 中建立檔案,然後複製到以下程式碼中,將輔助字幕新增至查詢。

    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. 執行程式碼。

    npm run build && node -r dotenv/config dist/semanticQueryReturnCaptions.js
    
  3. 輸出應該包含新的標題元素與搜尋欄位。 標題是結果中最相關的段落。 如果您的索引包含較大的文字區塊,標題有助於擷取最有趣的句子。

    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.
    

傳回語意答案

這最後一個查詢會傳回語意答案。

語意排名器可以產生具有問題特性的查詢字串答案。 產生的答案會從您的內容中逐字擷取,因此它不會包含撰寫的內容,例如您從聊天完成模型預期的內容。 如果語意答案不適用於您的案例,您可以從程式代碼中省略 semantic_answers

若要產生語意答案,問題與答案必須緊密對齊,而且模型必須尋找清楚回答問題的內容。 若潛在答案未達信賴等級閾值,模型不會傳回答案。 在此為了示範,範例的問題已經過設計,可取得回應,以供您檢視語法。

  1. 在名為 ./srcsemanticAnswer.ts 中建立檔案,然後複製到以下程式碼中,取得語意答案。

    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. 執行程式碼。

    npm run build && node -r dotenv/config dist/semanticAnswer.js
    
  3. 輸出看起來應該類似下列範例,其中從其中一個結果提取問題的最佳答案。

    回想一下,答案為從您的索引中提取之逐字內容,因此,可能會缺少使用者預期看到的片語。 若要取得聊天完成模型所產生的 組成答案 ,請考慮使用 RAG模式代理程式擷取

    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
    

清除資源

使用您自己的訂用帳戶時,在專案結束後確認您是否還需要您建立的資源,是很好的做法。 讓資源繼續執行可能會產生費用。 您可以個別刪除資源,或刪除資源群組以刪除整組資源。

您可以在 Azure 入口網站中使用左瀏覽窗格中的 [所有資源] 或 [資源群組] 連結,以尋找和管理資源。

本快速入門說明如何針對現有索引叫用語意排名。 下一步,建議您針對自己的索引嘗試語意排名。 下列文章可協助您開始使用。