이 빠른 시작에서는 검색 인덱스로 의미 체계 구성을 추가하고 의미 체계 매개 변수를 쿼리에 추가하여 의미 체계 순위를 사용하는 방법을 알아봅니다. 호텔 샘플 인덱스 또는 사용자 고유의 인덱스 중 하나를 사용할 수 있습니다.
Azure AI Search에서 의미 체계 순위는 Microsoft의 컴퓨터 읽기 이해력을 사용하여 검색 결과를 다시 점수 매칭하여 가장 의미상 관련성이 높은 일치 항목을 목록 맨 위로 승격하는 쿼리 쪽 기능입니다. 콘텐츠 및 쿼리에 따라 의미 체계 순위는 최소한의 개발자 노력으로 검색 관련성을 크게 향상시킬 수 있습니다.
다시 빌드 요구 사항 없이 기존 인덱스로 의미 체계 구성을 추가할 수 있습니다. 의미 체계 순위는 정보 또는 설명이 있는 텍스트에 가장 효과적입니다.
필수 구성 요소
활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
검색 가능으로 특성이 지정된 설명적 텍스트 필드 또는 자세한 텍스트 필드가 있는 새 인덱스 또는 기존 인덱스. 이 빠른 시작에서는 hotels-sample-index를 가정합니다.
액세스 구성
역할 할당이 있는 API 키 또는 Microsoft Entra ID를 사용하여 Azure AI Search 서비스에 연결할 수 있습니다. 키는 시작하기가 더 쉽지만 역할이 더 안전합니다. 자세한 내용은 역할을 사용하여 Azure AI 검색에 연결을 참조하세요.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 선택합니다.
왼쪽 창에서 설정>키를 선택합니다.
API 액세스 제어에서 역할 기반 액세스 제어를 선택하거나 클라이언트를 역할 기반 액세스로 전환할 시간이 필요한 경우 둘 다 선택합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
추가>역할 할당 추가를 선택합니다.
사용자 계정에 Search Service 기여자 및 검색 인덱스 데이터 기여자 역할을 할당합니다.
인덱스로 시작
이 빠른 시작에서는 기존 인덱스를 가정하고 의미 체계 구성을 포함하도록 수정합니다. Azure Portal 마법사를 사용하여 몇 분 안에 만들 수 있는 hotels-sample-index 를 사용하는 것이 좋습니다.
기존 인덱스로 시작하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 찾습니다.
검색 관리>인덱스 아래에서 hotels-sample-index를 선택합니다.
의미 체계 구성을 선택하여 인덱스에 의미 체계 구성이 없는지 확인합니다.
검색 탐색기를 선택한 다음 JSON 보기를 선택합니다.
다음 JSON을 쿼리 편집기에 붙여넣습니다.
{ "search": "walking distance to live music", "select": "HotelId, HotelName, Description", "count": true }
쿼리를 실행하려면 쿼리를 선택합니다.
이 쿼리는 키워드 검색입니다. 응답은 전체 텍스트 검색을 위해 기본 BM25 L1 순위에 의해 점수가 매겨진 다음 예제와 유사해야 합니다.
가독성을 위해 예제에서는 ,
HotelId및HotelName필드만 선택합니다Description. 결과에는 쿼리 용어 (walking,distance,live,music) 또는 언어 변형 (walk,living)에 대한 직접 일치 결과가 포함됩니다."@odata.count": 13, "value": [ { "@search.score": 5.5153193, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 5.074317, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." }, { "@search.score": 4.8959594, "HotelId": "4", "HotelName": "Sublime Palace Hotel", "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience." }, { "@search.score": 2.5966604, "HotelId": "35", "HotelName": "Bellevue Suites", "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport." }, { "@search.score": 2.566386, "HotelId": "47", "HotelName": "Country Comfort Inn", "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome." }, { "@search.score": 2.2405157, "HotelId": "9", "HotelName": "Smile Up Hotel", "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene." }, { "@search.score": 2.1737604, "HotelId": "8", "HotelName": "Foot Happy Suites", "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further." }, { "@search.score": 2.0364518, "HotelId": "31", "HotelName": "Country Residence Hotel", "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door." }, { "@search.score": 1.7595702, "HotelId": "49", "HotelName": "Swirling Currents Hotel", "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. " }, { "@search.score": 1.5502293, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3302404, "HotelId": "42", "HotelName": "Rock Bottom Resort & Campground", "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away." }, { "@search.score": 0.9050383, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 0.7334347, "HotelId": "39", "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings." } ]
이 쿼리는 의미 체계 순위가 적용 되기 전에 응답이 어떻게 보이는지 보여줍니다. 나중에 의미 체계 순위가 구성된 후 동일한 쿼리를 실행하여 응답이 어떻게 변경되는지 확인할 수 있습니다.
팁 (조언)
Azure Portal에서 의미 체계 구성을 추가할 수 있습니다. 그러나 프로그래밍 방식으로 의미 체계 구성을 추가하는 방법을 알아보려면 이 빠른 시작을 계속 진행합니다.
클라이언트 설정
이 빠른 시작에서는 IDE 및 Azure.Search.Documents 클라이언트 라이브러리를 사용하여 기존 검색 인덱스로 의미 체계 순위를 추가합니다.
이 빠른 시작에는 Visual Studio 를 사용하는 것이 좋습니다.
팁 (조언)
소스 코드를 다운로드하여 완료된 프로젝트로 시작하거나 다음 단계에 따라 직접 만들 수 있습니다.
라이브러리 설치
Visual Studio를 시작하고 quickstart-semantic-search.sln 열거나 콘솔 애플리케이션 템플릿을 사용하여 새 프로젝트를 만듭니다.
도구>NuGet 패키지 관리자에서 솔루션의 NuGet 패키지 관리...를 선택합니다.
찾아보기를 선택합니다.
Azure.Search.Documents 패키지를 검색하고 최신 안정 버전을 선택합니다.
Azure.Identity 패키지를 검색하고 안정적인 최신 버전을 선택합니다.
설치를 선택하여 프로젝트 및 솔루션에 어셈블리를 추가합니다.
Azure에 로그인
Azure Portal에 로그인한 경우 Azure에 로그인됩니다. 확실하지 않은 경우 Azure CLI 또는 Azure PowerShell을 사용하여 로그인 az login 합니다. 또는 az connect. 여러 테넌트 및 구독이 있는 경우 빠른 시작을 참조하세요. 연결 방법에 대한 도움말을 보려면 키 없이 연결 합니다.
인덱스 업데이트
이 섹션에서는 의미 체계 구성을 포함하도록 검색 인덱스 업데이트 코드는 검색 서비스에서 인덱스 정의를 가져오고 의미 체계 구성을 추가합니다.
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; } }검색 서비스 URL을 유효한 엔드포인트로 바꿉다.
프로그램을 실행합니다.
출력은 Console.WriteLine에서 콘솔 창에 기록됩니다. 새 의미 체계 구성이 포함된 인덱스 스키마의 JSON을 포함하여 각 단계에 대한 메시지가 표시됩니다.
의미 체계 쿼리 실행
이 섹션에서는 여러 의미 체계 쿼리를 순서대로 실행합니다.
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}"); } } } }검색 서비스 URL을 유효한 엔드포인트로 바꿉다.
프로그램을 실행합니다.
출력은 Console.WriteLine에서 콘솔 창에 기록됩니다. 각 쿼리에 대한 검색 결과가 표시됩니다.
의미 체계 쿼리에 대한 출력(캡션 또는 답변 없음)
이 출력은 캡션이나 답변이 없는 의미 체계 쿼리에서 가져옵니다. 쿼리 문자열은 '라이브 음악까지 도보 거리'입니다.
여기서 용어 쿼리의 초기 결과는 의미 체계 순위 모델을 사용하여 다시 점수가 지정됩니다. 이 특정 데이터 세트 및 쿼리의 경우 처음 몇 가지 결과는 비슷한 위치에 있습니다. 의미 체계 순위의 효과는 결과의 나머지 부분에서 더 두드러집니다.
HotelId: 24
HotelName: Uptown Chic Hotel
Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
@search.score: 5.074317
@search.rerankerScore: 2.613231658935547
----------------------------------------
HotelId: 2
HotelName: Old Century Hotel
Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.
@search.score: 5.5153193
@search.rerankerScore: 2.271434783935547
----------------------------------------
HotelId: 4
HotelName: Sublime Palace Hotel
Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.
@search.score: 4.8959594
@search.rerankerScore: 1.9861756563186646
----------------------------------------
HotelId: 39
HotelName: White Mountain Lodge & Suites
Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.
@search.score: 0.7334347
@search.rerankerScore: 1.9615401029586792
----------------------------------------
HotelId: 15
HotelName: By the Market Hotel
Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.
@search.score: 1.5502293
@search.rerankerScore: 1.9085469245910645
----------------------------------------
Press Enter to continue to the next query...
캡션이 있는 의미 체계 쿼리에 대한 출력
다음은 '히트 하이라이트'가 적용된 캡션을 추가하는 검색 쿼리의 결과입니다.
Caption: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.
HotelId: 24
HotelName: Uptown Chic Hotel
Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.
@search.score: 5.074317
@search.rerankerScore: 2.613231658935547
----------------------------------------
Caption:
HotelId: 2
HotelName: Old Century Hotel
Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.
@search.score: 5.5153193
@search.rerankerScore: 2.271434783935547
----------------------------------------
Caption: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within<em> short walking distance </em>to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort,.
HotelId: 4
HotelName: Sublime Palace Hotel
Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.
@search.score: 4.8959594
@search.rerankerScore: 1.9861756563186646
----------------------------------------
Caption: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend<em> evening entertainment </em>on the patio features special<em> guest musicians </em>or.
HotelId: 39
HotelName: White Mountain Lodge & Suites
Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.
@search.score: 0.7334347
@search.rerankerScore: 1.9615401029586792
----------------------------------------
Caption: Book now and Save up to 30%. Central location. <em>Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood.</em> Brand new rooms. Impeccable service.
HotelId: 15
HotelName: By the Market Hotel
Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.
@search.score: 1.5502293
@search.rerankerScore: 1.9085469245910645
----------------------------------------
Press Enter to continue to the next query...
의미론적 답변에 대한 출력
최종 쿼리는 의미 체계 대답을 반환합니다. 이 예제의 쿼리 문자열을 변경했습니다. '읽는 것을 좋아하는 사람들에게 좋은 호텔이란?'.
의미 체계 순위는 질문의 특징이 있는 쿼리 문자열에 대한 답변을 생성할 수 있습니다. 생성된 답변은 콘텐츠에서 축자식으로 추출되므로 채팅 완료 모델에서 기대할 수 있는 것과 같은 구성된 콘텐츠는 포함되지 않습니다. 의미 체계 답변이 시나리오에 유용하지 않은 경우 코드에서 생략 semantic_answers 할 수 있습니다.
의미 체계 답변을 생성하려면 질문과 대답을 긴밀하게 정렬해야 하며 모델은 질문에 명확하게 답변하는 콘텐츠를 찾아야 합니다. 잠재적인 답변이 신뢰도 임계값을 충족하지 못하면 모델은 답변을 반환하지 않습니다. 이 예제의 질문은 데모 목적으로 응답을 가져오도록 설계되었으므로 구문을 볼 수 있습니다.
답변은 귀하의 인덱스에서 추출된 원문 그대로의 콘텐츠이며, 사용자가 예상하는 문구가 누락되어 있을 수도 있습니다. 채팅 완료 모델에서 생성된 구성된 답변을 가져오려면 RAG 패턴이나 에이전트 검색을 사용하는 것이 좋습니다.
Extractive Answers:
Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
----------------------------------------
HotelId: 1
HotelName: Stay-Kay City Hotel
Description: This classic hotel is fully-refurbished and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.
@search.score: 2.0361428
@search.rerankerScore: 2.124817371368408
----------------------------------------
HotelId: 16
HotelName: Double Sanctuary Resort
Description: 5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.
@search.score: 3.759768
@search.rerankerScore: 2.0705394744873047
----------------------------------------
HotelId: 38
HotelName: Lakeside B & B
Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.
@search.score: 0.7308748
@search.rerankerScore: 2.041472911834717
----------------------------------------
HotelId: 2
HotelName: Old Century Hotel
Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.
@search.score: 3.391012
@search.rerankerScore: 2.0231292247772217
----------------------------------------
HotelId: 15
HotelName: By the Market Hotel
Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.
@search.score: 1.3198771
@search.rerankerScore: 2.021622657775879
----------------------------------------
이 빠른 시작에서는 검색 인덱스로 의미 체계 구성을 추가하고 의미 체계 매개 변수를 쿼리에 추가하여 의미 체계 순위를 사용하는 방법을 알아봅니다. 호텔 샘플 인덱스 또는 사용자 고유의 인덱스 중 하나를 사용할 수 있습니다.
Azure AI Search에서 의미 체계 순위는 Microsoft의 컴퓨터 읽기 이해력을 사용하여 검색 결과를 다시 점수 매칭하여 가장 의미상 관련성이 높은 일치 항목을 목록 맨 위로 승격하는 쿼리 쪽 기능입니다. 콘텐츠 및 쿼리에 따라 의미 체계 순위는 최소한의 개발자 노력으로 검색 관련성을 크게 향상시킬 수 있습니다.
다시 빌드 요구 사항 없이 기존 인덱스로 의미 체계 구성을 추가할 수 있습니다. 의미 체계 순위는 정보 또는 설명이 있는 텍스트에 가장 효과적입니다.
필수 구성 요소
활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
검색 가능으로 특성이 지정된 설명적 텍스트 필드 또는 자세한 텍스트 필드가 있는 새 인덱스 또는 기존 인덱스. 이 빠른 시작에서는 hotels-sample-index를 가정합니다.
액세스 구성
역할 할당이 있는 API 키 또는 Microsoft Entra ID를 사용하여 Azure AI Search 서비스에 연결할 수 있습니다. 키는 시작하기가 더 쉽지만 역할이 더 안전합니다. 자세한 내용은 역할을 사용하여 Azure AI 검색에 연결을 참조하세요.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 선택합니다.
왼쪽 창에서 설정>키를 선택합니다.
API 액세스 제어에서 역할 기반 액세스 제어를 선택하거나 클라이언트를 역할 기반 액세스로 전환할 시간이 필요한 경우 둘 다 선택합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
추가>역할 할당 추가를 선택합니다.
사용자 계정에 Search Service 기여자 및 검색 인덱스 데이터 기여자 역할을 할당합니다.
인덱스로 시작
이 빠른 시작에서는 기존 인덱스를 가정하고 의미 체계 구성을 포함하도록 수정합니다. Azure Portal 마법사를 사용하여 몇 분 안에 만들 수 있는 hotels-sample-index 를 사용하는 것이 좋습니다.
기존 인덱스로 시작하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 찾습니다.
검색 관리>인덱스 아래에서 hotels-sample-index를 선택합니다.
의미 체계 구성을 선택하여 인덱스에 의미 체계 구성이 없는지 확인합니다.
검색 탐색기를 선택한 다음 JSON 보기를 선택합니다.
다음 JSON을 쿼리 편집기에 붙여넣습니다.
{ "search": "walking distance to live music", "select": "HotelId, HotelName, Description", "count": true }
쿼리를 실행하려면 쿼리를 선택합니다.
이 쿼리는 키워드 검색입니다. 응답은 전체 텍스트 검색을 위해 기본 BM25 L1 순위에 의해 점수가 매겨진 다음 예제와 유사해야 합니다.
가독성을 위해 예제에서는 ,
HotelId및HotelName필드만 선택합니다Description. 결과에는 쿼리 용어 (walking,distance,live,music) 또는 언어 변형 (walk,living)에 대한 직접 일치 결과가 포함됩니다."@odata.count": 13, "value": [ { "@search.score": 5.5153193, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 5.074317, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." }, { "@search.score": 4.8959594, "HotelId": "4", "HotelName": "Sublime Palace Hotel", "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience." }, { "@search.score": 2.5966604, "HotelId": "35", "HotelName": "Bellevue Suites", "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport." }, { "@search.score": 2.566386, "HotelId": "47", "HotelName": "Country Comfort Inn", "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome." }, { "@search.score": 2.2405157, "HotelId": "9", "HotelName": "Smile Up Hotel", "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene." }, { "@search.score": 2.1737604, "HotelId": "8", "HotelName": "Foot Happy Suites", "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further." }, { "@search.score": 2.0364518, "HotelId": "31", "HotelName": "Country Residence Hotel", "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door." }, { "@search.score": 1.7595702, "HotelId": "49", "HotelName": "Swirling Currents Hotel", "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. " }, { "@search.score": 1.5502293, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3302404, "HotelId": "42", "HotelName": "Rock Bottom Resort & Campground", "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away." }, { "@search.score": 0.9050383, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 0.7334347, "HotelId": "39", "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings." } ]
이 쿼리는 의미 체계 순위가 적용 되기 전에 응답이 어떻게 보이는지 보여줍니다. 나중에 의미 체계 순위가 구성된 후 동일한 쿼리를 실행하여 응답이 어떻게 변경되는지 확인할 수 있습니다.
팁 (조언)
Azure Portal에서 의미 체계 구성을 추가할 수 있습니다. 그러나 프로그래밍 방식으로 의미 체계 구성을 추가하는 방법을 알아보려면 이 빠른 시작을 계속 진행합니다.
클라이언트 설정
이 빠른 시작에서는 IDE 및 @azure/search-documents 클라이언트 라이브러리를 사용하여 기존 검색 인덱스로 의미 체계 순위를 추가합니다.
빠른 시작에서는 컴퓨터에서 다음을 사용할 수 있다고 가정합니다.
- 이 빠른 시작을 위해 Visual Studio Code를 사용합니다.
- 샘플을 실행하기 위한 Node.js (LTS)입니다.
팁 (조언)
소스 코드를 다운로드하여 완료된 프로젝트로 시작하거나 다음 단계에 따라 직접 만들 수 있습니다.
로컬 개발 환경 설정
새 디렉터리에서 Visual Studio Code를 시작합니다.
mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart code .프로젝트 디렉터리에서 ESM 모듈에 대한 새 패키지를 만듭니다.
npm init -y npm pkg set type=moduleazure-search-documents를 포함한 패키지를 설치합니다.
npm install @azure/identity @azure/search-documents dotenv.env를 만들고 검색 서비스 엔드포인트를 제공하세요. 검색 서비스 개요 페이지의 Azure Portal에서 엔드포인트를 가져올 수 있습니다.AZURE_SEARCH_ENDPOINT=YOUR-SEARCH-SERVICE-ENDPOINT AZURE_SEARCH_INDEX_NAME=hotels-sample-index SEMANTIC_CONFIGURATION_NAME=semantic-configsrc프로젝트 디렉터리에 디렉터리를 만듭니다.mkdir src
Azure에 로그인
Azure Portal에 로그인한 경우 Azure에 로그인됩니다. 확실하지 않은 경우 Azure CLI 또는 Azure PowerShell을 사용하여 로그인 az login 합니다. 또는 az connect. 여러 테넌트 및 구독이 있는 경우 빠른 시작을 참조하세요. 연결 방법에 대한 도움말을 보려면 키 없이 연결 합니다.
일반 인증 파일 만들기
./src에 config.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 인덱스 설정을 가져옵니다.
./src에getIndexSettings.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."); }코드를 실행합니다.
node -r dotenv/config src/getIndexSettings.js출력은 인덱스의 이름, 필드 목록 및 의미 체계 구성이 존재하는지 여부를 나타내는 문입니다. 빠른 시작을 위해 메시지가
No semantic configuration exists for this index라고 해야 합니다.
의미 체계 구성으로 인덱스 업데이트
./src디렉토리에updateIndexSettings.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); }코드를 실행합니다.
node -r dotenv/config src/updateIndexSettings.js출력은 방금 추가
Semantic configuration updated successfully.한 의미 체계 구성입니다.
의미 체계 쿼리 실행
인덱스에 hotels-sample-index 의미 체계 구성이 있으면 의미 체계 매개 변수를 포함하는 쿼리를 실행할 수 있습니다.
./src에semanticQuery.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`); }코드를 실행합니다.
node -r dotenv/config src/semanticQuery.js출력은 13개의 문서로 구성되어야 하며 순서는 다음과 같습니다
rerankerScoreDisplay.
캡션 반환
필요에 따라 캡션을 추가하여 텍스트의 일부를 추출하고 중요한 용어 및 구에 적중 항목 강조 표시를 적용할 수 있습니다. 이 쿼리는 캡션을 추가합니다.
호출
./src된semanticQueryReturnCaptions.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)); }코드를 실행합니다.
node -r dotenv/config src/semanticQueryReturnCaptions.js출력에는 검색 필드와 함께 새 캡션 요소가 포함되어야 합니다. 캡션은 결과에서 가장 관련성이 큰 구절입니다. 인덱스에 더 큰 텍스트 청크가 포함된 경우 캡션은 가장 흥미로운 문장을 추출하는 데 유용합니다.
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 할 수 있습니다.
의미 체계 답변을 생성하려면 질문과 대답을 긴밀하게 정렬해야 하며 모델은 질문에 명확하게 답변하는 콘텐츠를 찾아야 합니다. 잠재적인 답변이 신뢰도 임계값을 충족하지 못하면 모델은 답변을 반환하지 않습니다. 이 예제의 질문은 데모 목적으로 응답을 가져오도록 설계되었으므로 구문을 볼 수 있습니다.
./src에semanticAnswer.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`); } } }코드를 실행합니다.
node -r dotenv/config src/semanticAnswer.js출력은 다음 예제와 유사하게 표시됩니다. 여기서 질문에 대한 최상의 답변은 결과 중 하나에서 가져옵니다.
답변은 귀하의 인덱스에서 추출된 원문 그대로의 콘텐츠이며, 사용자가 예상하는 문구가 누락되어 있을 수도 있습니다. 채팅 완료 모델에서 생성된 구성된 답변을 가져오려면 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 AI Search에서 의미 체계 순위는 Microsoft의 컴퓨터 읽기 이해력을 사용하여 검색 결과를 다시 점수 매칭하여 가장 의미상 관련성이 높은 일치 항목을 목록 맨 위로 승격하는 쿼리 쪽 기능입니다. 콘텐츠 및 쿼리에 따라 의미 체계 순위는 최소한의 개발자 노력으로 검색 관련성을 크게 향상시킬 수 있습니다.
다시 빌드 요구 사항 없이 기존 인덱스로 의미 체계 구성을 추가할 수 있습니다. 의미 체계 순위는 정보 또는 설명이 있는 텍스트에 가장 효과적입니다.
필수 구성 요소
활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
검색 가능으로 특성이 지정된 설명적 텍스트 필드 또는 자세한 텍스트 필드가 있는 새 인덱스 또는 기존 인덱스. 이 빠른 시작에서는 hotels-sample-index를 가정합니다.
액세스 구성
역할 할당이 있는 API 키 또는 Microsoft Entra ID를 사용하여 Azure AI Search 서비스에 연결할 수 있습니다. 키는 시작하기가 더 쉽지만 역할이 더 안전합니다. 자세한 내용은 역할을 사용하여 Azure AI 검색에 연결을 참조하세요.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 선택합니다.
왼쪽 창에서 설정>키를 선택합니다.
API 액세스 제어에서 역할 기반 액세스 제어를 선택하거나 클라이언트를 역할 기반 액세스로 전환할 시간이 필요한 경우 둘 다 선택합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
추가>역할 할당 추가를 선택합니다.
사용자 계정에 Search Service 기여자 및 검색 인덱스 데이터 기여자 역할을 할당합니다.
인덱스로 시작
이 빠른 시작에서는 기존 인덱스를 가정하고 의미 체계 구성을 포함하도록 수정합니다. Azure Portal 마법사를 사용하여 몇 분 안에 만들 수 있는 hotels-sample-index 를 사용하는 것이 좋습니다.
기존 인덱스로 시작하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 찾습니다.
검색 관리>인덱스 아래에서 hotels-sample-index를 선택합니다.
의미 체계 구성을 선택하여 인덱스에 의미 체계 구성이 없는지 확인합니다.
검색 탐색기를 선택한 다음 JSON 보기를 선택합니다.
다음 JSON을 쿼리 편집기에 붙여넣습니다.
{ "search": "walking distance to live music", "select": "HotelId, HotelName, Description", "count": true }
쿼리를 실행하려면 쿼리를 선택합니다.
이 쿼리는 키워드 검색입니다. 응답은 전체 텍스트 검색을 위해 기본 BM25 L1 순위에 의해 점수가 매겨진 다음 예제와 유사해야 합니다.
가독성을 위해 예제에서는 ,
HotelId및HotelName필드만 선택합니다Description. 결과에는 쿼리 용어 (walking,distance,live,music) 또는 언어 변형 (walk,living)에 대한 직접 일치 결과가 포함됩니다."@odata.count": 13, "value": [ { "@search.score": 5.5153193, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 5.074317, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." }, { "@search.score": 4.8959594, "HotelId": "4", "HotelName": "Sublime Palace Hotel", "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience." }, { "@search.score": 2.5966604, "HotelId": "35", "HotelName": "Bellevue Suites", "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport." }, { "@search.score": 2.566386, "HotelId": "47", "HotelName": "Country Comfort Inn", "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome." }, { "@search.score": 2.2405157, "HotelId": "9", "HotelName": "Smile Up Hotel", "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene." }, { "@search.score": 2.1737604, "HotelId": "8", "HotelName": "Foot Happy Suites", "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further." }, { "@search.score": 2.0364518, "HotelId": "31", "HotelName": "Country Residence Hotel", "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door." }, { "@search.score": 1.7595702, "HotelId": "49", "HotelName": "Swirling Currents Hotel", "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. " }, { "@search.score": 1.5502293, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3302404, "HotelId": "42", "HotelName": "Rock Bottom Resort & Campground", "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away." }, { "@search.score": 0.9050383, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 0.7334347, "HotelId": "39", "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings." } ]
이 쿼리는 의미 체계 순위가 적용 되기 전에 응답이 어떻게 보이는지 보여줍니다. 나중에 의미 체계 순위가 구성된 후 동일한 쿼리를 실행하여 응답이 어떻게 변경되는지 확인할 수 있습니다.
팁 (조언)
Azure Portal에서 의미 체계 구성을 추가할 수 있습니다. 그러나 프로그래밍 방식으로 의미 체계 구성을 추가하는 방법을 알아보려면 이 빠른 시작을 계속 진행합니다.
클라이언트 설정
이 빠른 시작에서는 IDE 및 Azure AI Search Java SDK 클라이언트 라이브러리를 사용하여 기존 검색 인덱스로 의미 체계 순위를 추가합니다.
빠른 시작에서는 컴퓨터에서 다음을 사용할 수 있다고 가정합니다.
- Java 확장 또는 IntelliJ IDEA를 사용하는 Visual Studio Code
- Java 21(LTS).
- Maven.
로컬 개발 환경 설정
새 Maven 프로젝트 디렉터리를 만듭니다.
mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart code .필수 종속성이 있는
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>프로젝트를 컴파일하여 종속성을 확인합니다.
mvn compile원본 디렉터리 구조를 만듭니다.
mkdir -p src/main/java/com/azure/search/quickstart mkdir -p src/main/resourcessrc/main/resources디렉터리에application.properties파일을 만들고 검색 서비스 엔드포인트를 입력합니다. 검색 서비스 개요 페이지의 Azure Portal에서 엔드포인트를 가져올 수 있습니다.azure.search.endpoint=YOUR-SEARCH-SERVICE-ENDPOINT azure.search.index.name=hotels-sample-index semantic.configuration.name=semantic-config
Azure에 로그인
Azure Portal에 로그인한 경우 Azure에 로그인됩니다. 확실하지 않은 경우 Azure CLI를 사용하여 로그인 az login합니다. 여러 테넌트 및 구독이 있는 경우 빠른 시작을 참조하세요. 연결 방법에 대한 도움말을 보려면 키 없이 연결 합니다.
공통 구성 클래스 만들기
src/main/java/com/azure/search/quickstart 디렉터리에 SearchConfig.java 파일을 생성하여 속성 파일을 읽고 구성 값과 인증 자격 증명을 저장합니다.
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 인덱스 설정을 가져옵니다.
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); } }코드를 컴파일하고 실행합니다.
mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.GetIndexSettings"출력은 인덱스의 이름, 필드 목록 및 의미 체계 구성이 존재하는지 여부를 나타내는 문입니다. 빠른 시작을 위해 메시지가
No semantic configuration exists for this index라고 해야 합니다.
의미 체계 구성으로 인덱스 업데이트
src/main/java/com/azure/search/quickstart디렉터리에UpdateIndexSettings.java파일을 만들어 검색 서비스의 기존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()); } } }코드를 컴파일하고 실행합니다.
mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.UpdateIndexSettings"출력은 방금 추가
Semantic configuration updated successfully.한 의미 체계 구성입니다.
의미 체계 쿼리 실행
인덱스에 hotels-sample-index 의미 체계 구성이 있으면 의미 체계 매개 변수를 포함하는 쿼리를 실행할 수 있습니다.
src/main/java/com/azure/search/quickstart디렉터리에SemanticQuery.java파일을 만들어 인덱스의 시맨틱 쿼리를 만듭니다.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); } }코드를 컴파일하고 실행합니다.
mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticQuery"출력은 재정렬 점수에 따라 정렬된 13개의 문서로 구성되어야 합니다.
캡션 반환
필요에 따라 캡션을 추가하여 텍스트의 일부를 추출하고 중요한 용어 및 구에 적중 항목 강조 표시를 적용할 수 있습니다.
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); } }코드를 컴파일하고 실행합니다.
mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticQueryWithCaptions"출력에는 검색 필드와 함께 새 캡션 요소가 포함되어야 합니다. 캡션은 결과에서 가장 관련성이 큰 구절입니다. 인덱스에 더 큰 텍스트 청크가 포함된 경우 캡션은 가장 흥미로운 문장을 추출하는 데 유용합니다.
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.
의미 체계 답변 반환
이 최종 쿼리에서 의미 체계 답변을 반환합니다.
의미 체계 순위는 질문의 특징이 있는 쿼리 문자열에 대한 답변을 생성할 수 있습니다. 생성된 답변은 콘텐츠에서 축자식으로 추출되므로 채팅 완료 모델에서 기대할 수 있는 것과 같은 구성된 콘텐츠는 포함되지 않습니다.
의미 체계 답변을 생성하려면 질문과 대답을 긴밀하게 정렬해야 하며 모델은 질문에 명확하게 답변하는 콘텐츠를 찾아야 합니다. 잠재적인 답변이 신뢰도 임계값을 충족하지 못하면 모델은 답변을 반환하지 않습니다. 이 예제의 질문은 데모 목적으로 응답을 가져오도록 설계되었으므로 구문을 볼 수 있습니다.
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); } }코드를 컴파일하고 실행합니다.
mvn compile exec:java -Dexec.mainClass="com.azure.search.quickstart.SemanticAnswer"출력은 다음 예제와 유사하게 표시됩니다. 여기서 질문에 대한 최상의 답변은 결과 중 하나에서 가져옵니다.
답변은 귀하의 인덱스에서 추출된 원문 그대로의 콘텐츠이며, 사용자가 예상하는 문구가 누락되어 있을 수도 있습니다. 채팅 완료 모델에서 생성된 구성된 답변을 가져오려면 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 AI Search에서 의미 체계 순위는 Microsoft의 컴퓨터 읽기 이해력을 사용하여 검색 결과를 다시 점수 매칭하여 가장 의미상 관련성이 높은 일치 항목을 목록 맨 위로 승격하는 쿼리 쪽 기능입니다. 콘텐츠 및 쿼리에 따라 의미 체계 순위는 최소한의 개발자 노력으로 검색 관련성을 크게 향상시킬 수 있습니다.
다시 빌드 요구 사항 없이 기존 인덱스로 의미 체계 구성을 추가할 수 있습니다. 의미 체계 순위는 정보 또는 설명이 있는 텍스트에 가장 효과적입니다.
필수 구성 요소
활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
검색 가능으로 특성이 지정된 설명적 텍스트 필드 또는 자세한 텍스트 필드가 있는 새 인덱스 또는 기존 인덱스. 이 빠른 시작에서는 hotels-sample-index를 가정합니다.
액세스 구성
역할 할당이 있는 API 키 또는 Microsoft Entra ID를 사용하여 Azure AI Search 서비스에 연결할 수 있습니다. 키는 시작하기가 더 쉽지만 역할이 더 안전합니다. 자세한 내용은 역할을 사용하여 Azure AI 검색에 연결을 참조하세요.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 선택합니다.
왼쪽 창에서 설정>키를 선택합니다.
API 액세스 제어에서 역할 기반 액세스 제어를 선택하거나 클라이언트를 역할 기반 액세스로 전환할 시간이 필요한 경우 둘 다 선택합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
추가>역할 할당 추가를 선택합니다.
사용자 계정에 Search Service 기여자 및 검색 인덱스 데이터 기여자 역할을 할당합니다.
인덱스로 시작
이 빠른 시작에서는 기존 인덱스를 가정하고 의미 체계 구성을 포함하도록 수정합니다. Azure Portal 마법사를 사용하여 몇 분 안에 만들 수 있는 hotels-sample-index 를 사용하는 것이 좋습니다.
기존 인덱스로 시작하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 찾습니다.
검색 관리>인덱스 아래에서 hotels-sample-index를 선택합니다.
의미 체계 구성을 선택하여 인덱스에 의미 체계 구성이 없는지 확인합니다.
검색 탐색기를 선택한 다음 JSON 보기를 선택합니다.
다음 JSON을 쿼리 편집기에 붙여넣습니다.
{ "search": "walking distance to live music", "select": "HotelId, HotelName, Description", "count": true }
쿼리를 실행하려면 쿼리를 선택합니다.
이 쿼리는 키워드 검색입니다. 응답은 전체 텍스트 검색을 위해 기본 BM25 L1 순위에 의해 점수가 매겨진 다음 예제와 유사해야 합니다.
가독성을 위해 예제에서는 ,
HotelId및HotelName필드만 선택합니다Description. 결과에는 쿼리 용어 (walking,distance,live,music) 또는 언어 변형 (walk,living)에 대한 직접 일치 결과가 포함됩니다."@odata.count": 13, "value": [ { "@search.score": 5.5153193, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 5.074317, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." }, { "@search.score": 4.8959594, "HotelId": "4", "HotelName": "Sublime Palace Hotel", "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience." }, { "@search.score": 2.5966604, "HotelId": "35", "HotelName": "Bellevue Suites", "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport." }, { "@search.score": 2.566386, "HotelId": "47", "HotelName": "Country Comfort Inn", "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome." }, { "@search.score": 2.2405157, "HotelId": "9", "HotelName": "Smile Up Hotel", "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene." }, { "@search.score": 2.1737604, "HotelId": "8", "HotelName": "Foot Happy Suites", "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further." }, { "@search.score": 2.0364518, "HotelId": "31", "HotelName": "Country Residence Hotel", "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door." }, { "@search.score": 1.7595702, "HotelId": "49", "HotelName": "Swirling Currents Hotel", "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. " }, { "@search.score": 1.5502293, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3302404, "HotelId": "42", "HotelName": "Rock Bottom Resort & Campground", "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away." }, { "@search.score": 0.9050383, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 0.7334347, "HotelId": "39", "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings." } ]
이 쿼리는 의미 체계 순위가 적용 되기 전에 응답이 어떻게 보이는지 보여줍니다. 나중에 의미 체계 순위가 구성된 후 동일한 쿼리를 실행하여 응답이 어떻게 변경되는지 확인할 수 있습니다.
팁 (조언)
Azure Portal에서 의미 체계 구성을 추가할 수 있습니다. 그러나 프로그래밍 방식으로 의미 체계 구성을 추가하는 방법을 알아보려면 이 빠른 시작을 계속 진행합니다.
클라이언트 설정
이 빠른 시작에서는 Python용 Azure SDK의 Jupyter Notebook 및 azure-search-documents 라이브러리를 사용하여 의미 체계 순위에 대해 알아봅니다.
이 빠른 시작에서는 Python 3.10 이상 및 Python 확장을 사용하는 Visual Studio Code를 사용하는 것이 좋습니다.
팁 (조언)
완성된 전자 필기장을 다운로드하여 완성된 프로젝트로 시작하거나 다음 단계에 따라 직접 만들 수 있습니다.
이 빠른 시작에서는 가상 환경을 사용하는 것이 좋습니다.
Visual Studio Code를 시작합니다.
semantic-search-quickstart.ipynb 파일을 열거나 새 Notebook을 만듭니다.
Ctrl+Shift+P를 사용하여 명령 팔레트를 엽니다.
Python: 환경 만들기를 검색합니다.
Venv.선택Python 인터프리터를 선택합니다. 3.10 이상을 선택합니다.
설정하는 데 1분 정도 걸릴 수 있습니다. 문제가 발생하면 VS Code의 Python 환경을 참조하세요.
패키지 설치 및 환경 변수 설정
azure-search-documents를 포함한 패키지를 설치합니다.
! pip install -r requirements.txt --quietsample.env을.env로 이름을 변경하고, 검색 서비스 엔드포인트를 제공합니다. 검색 서비스 개요 페이지의 Azure Portal에서 엔드포인트를 가져올 수 있습니다.AZURE_SEARCH_ENDPOINT=https://your-search-service.search.windows.net AZURE_SEARCH_INDEX_NAME=hotels-sample-index
Azure에 로그인
Azure Portal에 로그인한 경우 Azure에 로그인됩니다. 확실하지 않은 경우 Azure CLI 또는 Azure PowerShell을 사용하여 로그인 az login 합니다. 또는 az connect. 여러 테넌트 및 구독이 있는 경우 빠른 시작을 참조하세요. 연결 방법에 대한 도움말을 보려면 키 없이 연결 합니다.
인덱스 업데이트
이 섹션에서는 의미 체계 구성을 포함하도록 검색 인덱스 업데이트 코드는 검색 서비스에서 인덱스 정의를 가져오고 의미 체계 구성을 추가합니다.
Visual Studio Code에서 semantic-search-quickstart.ipynb 파일을 열거나 새 파일을 만듭니다.
솔루션에 사용되는 변수를 제공합니다.
# 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")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}")코드를 실행합니다.
출력은 인덱스의 이름, 필드 목록 및 의미 체계 구성이 존재하는지 여부를 나타내는 문입니다. 이 빠른 시작의 목적을 위해 메시지는 "이 인덱스에 대한 의미 체계 구성이 없습니다"라고 말해야 합니다.
검색 서비스의 기존 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}")코드를 실행합니다.
출력은 방금 추가한 의미 체계 구성입니다.
의미 체계 쿼리 실행
인덱스에 의미 체계 구성이 있으면 의미 체계 매개 변수를 포함하는 쿼리를 실행할 수 있습니다.
의미 체계 쿼리 유형 및 의미 체계 구성을 포함하는 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']}")코드를 실행합니다.
출력은 13개의 문서로 구성되어야 하며 순서는 다음과 같습니다
"@search.reranker_score".
캡션 반환
필요에 따라 캡션을 추가하여 텍스트의 일부를 추출하고 중요한 용어 및 구에 적중 항목 강조 표시를 적용할 수 있습니다. 이 쿼리는 캡션을 추가합니다.
쿼리에
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.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 할 수 있습니다.
의미 체계 답변을 생성하려면 질문과 대답을 긴밀하게 정렬해야 하며 모델은 질문에 명확하게 답변하는 콘텐츠를 찾아야 합니다. 잠재적인 답변이 신뢰도 임계값을 충족하지 못하면 모델은 답변을 반환하지 않습니다. 이 예제의 질문은 데모 목적으로 응답을 가져오도록 설계되었으므로 구문을 볼 수 있습니다.
쿼리에
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")코드를 실행합니다.
출력은 다음 예제와 유사하게 표시됩니다. 여기서 질문에 대한 최상의 답변은 결과 중 하나에서 가져옵니다.
답변은 귀하의 인덱스에서 추출된 원문 그대로의 콘텐츠이며, 사용자가 예상하는 문구가 누락되어 있을 수도 있습니다. 채팅 완료 모델에서 생성된 구성된 답변을 가져오려면 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. ...
이 빠른 시작에서는 검색 인덱스로 의미 체계 구성을 추가하고 의미 체계 매개 변수를 쿼리에 추가하여 의미 체계 순위를 사용하는 방법을 알아봅니다. 호텔 샘플 인덱스 또는 사용자 고유의 인덱스 중 하나를 사용할 수 있습니다.
Azure AI Search에서 의미 체계 순위는 Microsoft의 컴퓨터 읽기 이해력을 사용하여 검색 결과를 다시 점수 매칭하여 가장 의미상 관련성이 높은 일치 항목을 목록 맨 위로 승격하는 쿼리 쪽 기능입니다. 콘텐츠 및 쿼리에 따라 의미 체계 순위는 최소한의 개발자 노력으로 검색 관련성을 크게 향상시킬 수 있습니다.
다시 빌드 요구 사항 없이 기존 인덱스로 의미 체계 구성을 추가할 수 있습니다. 의미 체계 순위는 정보 또는 설명이 있는 텍스트에 가장 효과적입니다.
필수 구성 요소
활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
검색 가능으로 특성이 지정된 설명적 텍스트 필드 또는 자세한 텍스트 필드가 있는 새 인덱스 또는 기존 인덱스. 이 빠른 시작에서는 hotels-sample-index를 가정합니다.
액세스 구성
역할 할당이 있는 API 키 또는 Microsoft Entra ID를 사용하여 Azure AI Search 서비스에 연결할 수 있습니다. 키는 시작하기가 더 쉽지만 역할이 더 안전합니다. 자세한 내용은 역할을 사용하여 Azure AI 검색에 연결을 참조하세요.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 선택합니다.
왼쪽 창에서 설정>키를 선택합니다.
API 액세스 제어에서 역할 기반 액세스 제어를 선택하거나 클라이언트를 역할 기반 액세스로 전환할 시간이 필요한 경우 둘 다 선택합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
추가>역할 할당 추가를 선택합니다.
사용자 계정에 Search Service 기여자 및 검색 인덱스 데이터 기여자 역할을 할당합니다.
인덱스로 시작
이 빠른 시작에서는 기존 인덱스를 가정하고 의미 체계 구성을 포함하도록 수정합니다. Azure Portal 마법사를 사용하여 몇 분 안에 만들 수 있는 hotels-sample-index 를 사용하는 것이 좋습니다.
기존 인덱스로 시작하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 찾습니다.
검색 관리>인덱스 아래에서 hotels-sample-index를 선택합니다.
의미 체계 구성을 선택하여 인덱스에 의미 체계 구성이 없는지 확인합니다.
검색 탐색기를 선택한 다음 JSON 보기를 선택합니다.
다음 JSON을 쿼리 편집기에 붙여넣습니다.
{ "search": "walking distance to live music", "select": "HotelId, HotelName, Description", "count": true }
쿼리를 실행하려면 쿼리를 선택합니다.
이 쿼리는 키워드 검색입니다. 응답은 전체 텍스트 검색을 위해 기본 BM25 L1 순위에 의해 점수가 매겨진 다음 예제와 유사해야 합니다.
가독성을 위해 예제에서는 ,
HotelId및HotelName필드만 선택합니다Description. 결과에는 쿼리 용어 (walking,distance,live,music) 또는 언어 변형 (walk,living)에 대한 직접 일치 결과가 포함됩니다."@odata.count": 13, "value": [ { "@search.score": 5.5153193, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 5.074317, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." }, { "@search.score": 4.8959594, "HotelId": "4", "HotelName": "Sublime Palace Hotel", "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience." }, { "@search.score": 2.5966604, "HotelId": "35", "HotelName": "Bellevue Suites", "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport." }, { "@search.score": 2.566386, "HotelId": "47", "HotelName": "Country Comfort Inn", "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome." }, { "@search.score": 2.2405157, "HotelId": "9", "HotelName": "Smile Up Hotel", "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene." }, { "@search.score": 2.1737604, "HotelId": "8", "HotelName": "Foot Happy Suites", "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further." }, { "@search.score": 2.0364518, "HotelId": "31", "HotelName": "Country Residence Hotel", "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door." }, { "@search.score": 1.7595702, "HotelId": "49", "HotelName": "Swirling Currents Hotel", "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. " }, { "@search.score": 1.5502293, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3302404, "HotelId": "42", "HotelName": "Rock Bottom Resort & Campground", "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away." }, { "@search.score": 0.9050383, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 0.7334347, "HotelId": "39", "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings." } ]
이 쿼리는 의미 체계 순위가 적용 되기 전에 응답이 어떻게 보이는지 보여줍니다. 나중에 의미 체계 순위가 구성된 후 동일한 쿼리를 실행하여 응답이 어떻게 변경되는지 확인할 수 있습니다.
팁 (조언)
Azure Portal에서 의미 체계 구성을 추가할 수 있습니다. 그러나 프로그래밍 방식으로 의미 체계 구성을 추가하는 방법을 알아보려면 이 빠른 시작을 계속 진행합니다.
클라이언트 설정
이 빠른 시작에서는 REST 클라이언트 및 Azure AI Search REST API 를 사용하여 의미 체계 순위자를 구성하고 사용합니다.
이 빠른 시작에서는 REST 클라이언트 확장을 사용하는 Visual Studio Code를 사용하는 것이 좋습니다.
팁 (조언)
소스 코드를 다운로드하여 완료된 프로젝트로 시작하거나 다음 단계에 따라 직접 만들 수 있습니다.
Visual Studio Code를 시작하고 semantic-search-index-update.rest 파일을 열거나 새 파일을 만듭니다.
맨 위에서 검색 서비스, 권한 부여 및 인덱스 이름에 대한 환경 변수를 설정합니다.
의 경우 @searchURLAzure Portal에 로그인하고 검색 서비스 개요 페이지에서 URL을 복사합니다.
의 경우 @personalAccessToken키 없이 Connect의 지침에 따라 개인 액세스 토큰을 가져옵니다.
연결을 테스트하려면 첫 번째 요청을 보냅니다.
### List existing indexes by name (verify the connection) GET {{searchUrl}}/indexes?api-version=2025-09-01&$select=name HTTP/1.1 Authorization: Bearer {{personalAccessToken}}요청 보내기를 선택합니다.
이 GET 요청에 대한 출력은 기존 인덱스 목록을 반환합니다. 이 빠른 시작에서 사용되는 hotels-sample-index를 포함하여 HTTP 200 성공 상태 코드와 인덱스 목록을 가져와야 합니다.
인덱스 업데이트
REST API를 사용하여 인덱스를 업데이트하려면 전체 스키마와 수정할 내용을 제공해야 합니다. 이 요청은 호텔 샘플 인덱스 스키마와 의미 체계 구성을 제공합니다. 수정은 다음 JSON으로 구성됩니다.
"semantic": {
"configurations": [
{
"name": "semantic-config",
"rankingOrder": "BoostedRerankerScore",
"prioritizedFields": {
"titleField": { "fieldName": "HotelName" },
"prioritizedContentFields": [{ "fieldName": "Description" }],
"prioritizedKeywordsFields": [{ "fieldName": "Tags" }]
}
}
]
}
인덱스 이름, 작업 및 전체 JSON 스키마를 지정하는 PUT 요청을 작성합니다. 스키마의 모든 필수 요소가 있어야 합니다. 이 요청에는 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" } ] } } ] } }요청 보내기를 선택합니다.
이 POST 요청에 대한 출력은 상태 메시지입니다
HTTP 200 Success.
의미 체계 쿼리 실행
필수 의미 매개변수에는 query_type 및 semantic_configuration_name가 포함됩니다. 다음은 최소 매개 변수를 사용하는 기본 의미 체계 쿼리의 예입니다.
semantic-search-query.rest 파일을 열거나 새 파일을 만듭니다.
파일 맨 위에서 검색 서비스, 권한 부여 및 인덱스 이름에 대한 환경 변수를 설정합니다.
의 경우 @searchURLAzure Portal에 로그인하고 검색 서비스 개요 페이지에서 URL을 복사합니다.
의 경우 @personalAccessToken키 없이 Connect의 지침에 따라 개인 액세스 토큰을 가져옵니다.
hotels-sample-index를 반환하는 GET 요청으로 연결을 테스트합니다.
GET {{searchUrl}}/indexes/hotels-sample-index?api-version=2025-09-01 HTTP/1.1 Authorization: Bearer {{personalAccessToken}}의미 체계 쿼리 유형 및 구성 이름을 포함하는 쿼리를 보냅니다.
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" }출력은 JSON 검색 결과로 구성됩니다. 13개의 호텔이 쿼리와 일치합니다. 상위 7개 항목이 이 예제에 포함됩니다.
{ "@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." } ] }
캡션 반환
필요에 따라 캡션을 추가하여 텍스트의 일부를 추출하고 중요한 용어 및 구에 적중 항목 강조 표시를 적용할 수 있습니다. 이 쿼리는 적중 항목 강조 표시를 포함하는 캡션을 추가합니다.
매개 변수를
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" }출력은 동일한 결과에
"@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 할 수 있습니다.
의미 체계 답변을 생성하려면 질문과 대답을 긴밀하게 정렬해야 하며 모델은 질문에 명확하게 답변하는 콘텐츠를 찾아야 합니다. 잠재적인 답변이 신뢰도 임계값을 충족하지 못하면 모델은 답변을 반환하지 않습니다. 이 예제의 질문은 데모 목적으로 응답을 가져오도록 설계되었으므로 구문을 볼 수 있습니다.
질문을 하는 검색 문자열을 사용하여 요청을 작성합니다.
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" }출력은 새 쿼리에 대한 41개의 결과로 구성되며, 읽고 싶은 사람들을 위한 호텔에 대한 쿼리의 질문에 대한 "@search.answers"가 있습니다.
답변은 귀하의 인덱스에서 추출된 원문 그대로의 콘텐츠이며, 사용자가 예상하는 문구가 누락되어 있을 수도 있습니다. 채팅 완료 모델에서 생성된 구성된 답변을 가져오려면 RAG 패턴이나 에이전트 검색을 사용하는 것이 좋습니다.
이 예제에서 대답은 질문에 적합한 것으로 간주됩니다.
{ "@odata.count": 41, "@search.answers": [ { "key": "38", "text": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.", "highlights": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.", "score": 0.9829999804496765 } ], "value": [ { "@search.score": 2.0361428, "@search.rerankerScore": 2.124817371368408, "HotelId": "1", "HotelName": "Stay-Kay City Hotel", "Description": "This classic hotel is fully-refurbished and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities." }, { "@search.score": 3.759768, "@search.rerankerScore": 2.0705394744873047, "HotelId": "16", "HotelName": "Double Sanctuary Resort", "Description": "5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room." }, { "@search.score": 0.7308748, "@search.rerankerScore": 2.041472911834717, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 3.391012, "@search.rerankerScore": 2.0231292247772217, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 1.3198771, "@search.rerankerScore": 2.021622657775879, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3983066, "@search.rerankerScore": 2.005582809448242, "HotelId": "5", "HotelName": "Red Tide Hotel", "Description": "On entering this charming hotel in Scarlet Harbor, you'll notice an uncommon blend of antiques, original artwork, and contemporary comforts that give this hotel its signature look. Each suite is furnished to accentuate the views and unique characteristics of the building's classic architecture. No two suites are alike. However, all guests are welcome in the mezzanine plaza, the surrounding gardens, and the northside terrace for evening refreshments." }, { "@search.score": 1.4815493, "@search.rerankerScore": 1.9739465713500977, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." } ] }
이 빠른 시작에서는 검색 인덱스로 의미 체계 구성을 추가하고 의미 체계 매개 변수를 쿼리에 추가하여 의미 체계 순위를 사용하는 방법을 알아봅니다. 호텔 샘플 인덱스 또는 사용자 고유의 인덱스 중 하나를 사용할 수 있습니다.
Azure AI Search에서 의미 체계 순위는 Microsoft의 컴퓨터 읽기 이해력을 사용하여 검색 결과를 다시 점수 매칭하여 가장 의미상 관련성이 높은 일치 항목을 목록 맨 위로 승격하는 쿼리 쪽 기능입니다. 콘텐츠 및 쿼리에 따라 의미 체계 순위는 최소한의 개발자 노력으로 검색 관련성을 크게 향상시킬 수 있습니다.
다시 빌드 요구 사항 없이 기존 인덱스로 의미 체계 구성을 추가할 수 있습니다. 의미 체계 순위는 정보 또는 설명이 있는 텍스트에 가장 효과적입니다.
필수 구성 요소
활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
검색 가능으로 특성이 지정된 설명적 텍스트 필드 또는 자세한 텍스트 필드가 있는 새 인덱스 또는 기존 인덱스. 이 빠른 시작에서는 hotels-sample-index를 가정합니다.
액세스 구성
역할 할당이 있는 API 키 또는 Microsoft Entra ID를 사용하여 Azure AI Search 서비스에 연결할 수 있습니다. 키는 시작하기가 더 쉽지만 역할이 더 안전합니다. 자세한 내용은 역할을 사용하여 Azure AI 검색에 연결을 참조하세요.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 선택합니다.
왼쪽 창에서 설정>키를 선택합니다.
API 액세스 제어에서 역할 기반 액세스 제어를 선택하거나 클라이언트를 역할 기반 액세스로 전환할 시간이 필요한 경우 둘 다 선택합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
추가>역할 할당 추가를 선택합니다.
사용자 계정에 Search Service 기여자 및 검색 인덱스 데이터 기여자 역할을 할당합니다.
인덱스로 시작
이 빠른 시작에서는 기존 인덱스를 가정하고 의미 체계 구성을 포함하도록 수정합니다. Azure Portal 마법사를 사용하여 몇 분 안에 만들 수 있는 hotels-sample-index 를 사용하는 것이 좋습니다.
기존 인덱스로 시작하려면 다음을 수행합니다.
Azure Portal에 로그인하고 검색 서비스를 찾습니다.
검색 관리>인덱스 아래에서 hotels-sample-index를 선택합니다.
의미 체계 구성을 선택하여 인덱스에 의미 체계 구성이 없는지 확인합니다.
검색 탐색기를 선택한 다음 JSON 보기를 선택합니다.
다음 JSON을 쿼리 편집기에 붙여넣습니다.
{ "search": "walking distance to live music", "select": "HotelId, HotelName, Description", "count": true }
쿼리를 실행하려면 쿼리를 선택합니다.
이 쿼리는 키워드 검색입니다. 응답은 전체 텍스트 검색을 위해 기본 BM25 L1 순위에 의해 점수가 매겨진 다음 예제와 유사해야 합니다.
가독성을 위해 예제에서는 ,
HotelId및HotelName필드만 선택합니다Description. 결과에는 쿼리 용어 (walking,distance,live,music) 또는 언어 변형 (walk,living)에 대한 직접 일치 결과가 포함됩니다."@odata.count": 13, "value": [ { "@search.score": 5.5153193, "HotelId": "2", "HotelName": "Old Century Hotel", "Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music." }, { "@search.score": 5.074317, "HotelId": "24", "HotelName": "Uptown Chic Hotel", "Description": "Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance." }, { "@search.score": 4.8959594, "HotelId": "4", "HotelName": "Sublime Palace Hotel", "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience." }, { "@search.score": 2.5966604, "HotelId": "35", "HotelName": "Bellevue Suites", "Description": "Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport." }, { "@search.score": 2.566386, "HotelId": "47", "HotelName": "Country Comfort Inn", "Description": "Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome." }, { "@search.score": 2.2405157, "HotelId": "9", "HotelName": "Smile Up Hotel", "Description": "Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene." }, { "@search.score": 2.1737604, "HotelId": "8", "HotelName": "Foot Happy Suites", "Description": "Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further." }, { "@search.score": 2.0364518, "HotelId": "31", "HotelName": "Country Residence Hotel", "Description": "All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door." }, { "@search.score": 1.7595702, "HotelId": "49", "HotelName": "Swirling Currents Hotel", "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. " }, { "@search.score": 1.5502293, "HotelId": "15", "HotelName": "By the Market Hotel", "Description": "Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service." }, { "@search.score": 1.3302404, "HotelId": "42", "HotelName": "Rock Bottom Resort & Campground", "Description": "Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away." }, { "@search.score": 0.9050383, "HotelId": "38", "HotelName": "Lakeside B & B", "Description": "Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply." }, { "@search.score": 0.7334347, "HotelId": "39", "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings." } ]
이 쿼리는 의미 체계 순위가 적용 되기 전에 응답이 어떻게 보이는지 보여줍니다. 나중에 의미 체계 순위가 구성된 후 동일한 쿼리를 실행하여 응답이 어떻게 변경되는지 확인할 수 있습니다.
팁 (조언)
Azure Portal에서 의미 체계 구성을 추가할 수 있습니다. 그러나 프로그래밍 방식으로 의미 체계 구성을 추가하는 방법을 알아보려면 이 빠른 시작을 계속 진행합니다.
클라이언트 설정
이 빠른 시작에서는 IDE 및 @azure/search-documents 클라이언트 라이브러리를 사용하여 기존 검색 인덱스로 의미 체계 순위를 추가합니다.
빠른 시작에서는 컴퓨터에서 다음을 사용할 수 있다고 가정합니다.
- 이 빠른 시작을 위해 Visual Studio Code를 사용합니다.
- 샘플을 실행하기 위한 Node.js (LTS)입니다.
- 샘플 코드를 작성하기 위한 TypeScript입니다.
팁 (조언)
소스 코드를 다운로드하여 완료된 프로젝트로 시작하거나 다음 단계에 따라 직접 만들 수 있습니다.
로컬 개발 환경 설정
새 디렉터리에서 Visual Studio Code를 시작합니다.
mkdir semantic-ranking-quickstart && cd semantic-ranking-quickstart code .프로젝트 디렉터리에서 ESM 모듈에 대한 새 패키지를 만듭니다.
npm init -y npm pkg set type=moduleazure-search-documents를 포함한 개발 패키지를 설치합니다.
npm install @azure/identity @azure/search-documents dotenv개발 종속성 패키지를 설치합니다.
npm install dotenv @types/node --save-devtsconfig.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" ] }TypeScript 파일을 빌드하기 위한 스크립트를 포함하도록 업데이트
package.json합니다. 섹션에 다음 줄을 추가합니다scripts."build": "tsc".env를 만들고 검색 서비스 엔드포인트를 제공하세요. 검색 서비스 개요 페이지의 Azure Portal에서 엔드포인트를 가져올 수 있습니다.AZURE_SEARCH_ENDPOINT=YOUR-SEARCH-SERVICE-ENDPOINT AZURE_SEARCH_INDEX_NAME=hotels-sample-index SEMANTIC_CONFIGURATION_NAME=semantic-configsrc프로젝트 디렉터리에 디렉터리를 만듭니다.mkdir src
Azure에 로그인
Azure Portal에 로그인한 경우 Azure에 로그인됩니다. 확실하지 않은 경우 Azure CLI 또는 Azure PowerShell을 사용하여 로그인 az login 합니다. 또는 az connect. 여러 테넌트 및 구독이 있는 경우 빠른 시작을 참조하세요. 연결 방법에 대한 도움말을 보려면 키 없이 연결 합니다.
일반 인증 파일 만들기
./src에 config.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 인덱스 설정을 가져옵니다.
./src에getIndexSettings.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."); }코드를 실행합니다.
npm run build && node -r dotenv/config dist/getIndexSettings.js출력은 인덱스의 이름, 필드 목록 및 의미 체계 구성이 존재하는지 여부를 나타내는 문입니다. 빠른 시작을 위해 메시지가
No semantic configuration exists for this index라고 해야 합니다.
의미 체계 구성으로 인덱스 업데이트
./src디렉토리에updateIndexSettings.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); }코드를 실행합니다.
npm run build && node -r dotenv/config dist/updateIndexSettings.js출력은 방금 추가
Semantic configuration updated successfully.한 의미 체계 구성입니다.
의미 체계 쿼리 실행
인덱스에 hotels-sample-index 의미 체계 구성이 있으면 의미 체계 매개 변수를 포함하는 쿼리를 실행할 수 있습니다.
./src에semanticQuery.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`); }코드를 실행합니다.
npm run build && node -r dotenv/config dist/semanticQuery.js출력은 13개의 문서로 구성되어야 하며 순서는 다음과 같습니다
rerankerScoreDisplay.
캡션 반환
필요에 따라 캡션을 추가하여 텍스트의 일부를 추출하고 중요한 용어 및 구에 적중 항목 강조 표시를 적용할 수 있습니다. 이 쿼리는 캡션을 추가합니다.
호출
./src된semanticQueryReturnCaptions.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)); }코드를 실행합니다.
npm run build && node -r dotenv/config dist/semanticQueryReturnCaptions.js출력에는 검색 필드와 함께 새 캡션 요소가 포함되어야 합니다. 캡션은 결과에서 가장 관련성이 큰 구절입니다. 인덱스에 더 큰 텍스트 청크가 포함된 경우 캡션은 가장 흥미로운 문장을 추출하는 데 유용합니다.
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 할 수 있습니다.
의미 체계 답변을 생성하려면 질문과 대답을 긴밀하게 정렬해야 하며 모델은 질문에 명확하게 답변하는 콘텐츠를 찾아야 합니다. 잠재적인 답변이 신뢰도 임계값을 충족하지 못하면 모델은 답변을 반환하지 않습니다. 이 예제의 질문은 데모 목적으로 응답을 가져오도록 설계되었으므로 구문을 볼 수 있습니다.
./src에semanticAnswer.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`); } } }코드를 실행합니다.
npm run build && node -r dotenv/config dist/semanticAnswer.js출력은 다음 예제와 유사하게 표시됩니다. 여기서 질문에 대한 최상의 답변은 결과 중 하나에서 가져옵니다.
답변은 귀하의 인덱스에서 추출된 원문 그대로의 콘텐츠이며, 사용자가 예상하는 문구가 누락되어 있을 수도 있습니다. 채팅 완료 모델에서 생성된 구성된 답변을 가져오려면 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 Portal에서 리소스를 찾고 관리할 수 있습니다.
관련 콘텐츠
이 빠른 시작에서는 기존 인덱스의 의미 체계 순위를 호출하는 방법을 알아보았습니다. 다음 단계로 사용자 고유의 인덱스에 대한 의미 체계 순위를 시도하는 것이 좋습니다. 다음 문서는 시작하는 데 도움이 될 수 있습니다.