共用方式為


快速入門:使用 REST API 進行向量搜尋

了解如何使用搜尋服務 REST API 在 Azure AI 搜尋服務中建立、載入及查詢向量。

在 Azure AI 搜尋中, 向量存放區 具有定義向量和非向量欄位的索引架構、用於建立內嵌空間之演算法的向量搜尋組態,以及查詢時評估的向量字段定義設定。 建立 索引 REST API 會建立向量存放區。

如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶

注意

本快速入門省略向量化步驟,並提供範例文件中的內嵌。 如果您想要將內建資料區塊化和向量化新增至您自己的內容,請嘗試匯入和向量化資料精靈,以取得完整的逐步解說。

必要條件

擷取資源資訊

對搜尋端點發出的要求必須經過驗證和授權。 您可以針對這項工作使用 API 金鑰或角色。 建議您 透過 Microsoft Entra ID 使用無密鑰連線。

選取對應至您慣用驗證方法的索引標籤。 在本快速入門中,針對所有要求使用相同的方法。

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

  2. 在 [概觀] 首頁上,尋找 URL。 範例端點看起來會像是 https://mydemo.search.windows.net

    概觀頁面上 URL 屬性的螢幕擷取畫面。

  3. 請遵循無密鑰快速入門中的步驟,取得您的Microsoft Entra 令牌。

    當您在上一個快速入門的步驟 3 中執行 az account get-access-token 命令時,您會取得令牌。

    az account get-access-token --scope https://search.azure.com/.default --query accessToken --output tsv
    

建立或下載程式代碼檔案

您可以使用一或.http.rest檔案來執行本快速入門中的所有要求。 您可以下載包含本快速入門程序代碼的 REST 檔案,或在 Visual Studio Code 中建立新檔案,並將程式代碼複製到其中。

  1. 在 Visual Studio Code 中,建立具有 .rest.http 擴展名的新檔案。 例如: az-search-vector-quickstart.rest 。 將 Azure-Samples/azure-search-rest-samples/blob/main/Quickstart-vectors/az-search-vector-quickstart.rest 檔案的原始內容複製並貼到這個新檔案中。

  2. 在檔案頂端,將的佔位元值 @baseUrl 取代為您的搜尋服務 URL。 如需如何尋找搜尋服務 URL 的指示,請參閱擷 取資源資訊 一節。

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
    
  3. 在檔案頂端,取代驗證的佔位元值。 如需如何取得Microsoft Entra 令牌或 API 金鑰的指示,請參閱擷取資源資訊一節。

    如需透過 Microsoft Entra ID 的建議無密鑰驗證,您必須將 取代@apiKey@token 變數。

    @token = PUT-YOUR-MICROSOFT-ENTRA-TOKEN-HERE
    

    如果您想要使用 API 金鑰,請將 取代@apiKey為您從 Azure 入口網站 複製的金鑰。

    @apiKey = PUT-YOUR-ADMIN-KEY-HERE
    
  4. 如需透過 Microsoft Entra ID 的建議無金鑰驗證,您必須在要求標頭中將 取代api-key: {{apiKey}}Authorization: Bearer {{token}} 。 取代您在檔案中找到的所有實例 api-key: {{apiKey}}

建立向量索引

您可以使用 建立索引 REST API 來建立向量索引,並在您的搜尋服務上設定實體數據結構。

此範例中的索引架構會圍繞旅館內容進行組織。 範例數據是由虛構旅館的向量和非向量名稱和描述所組成。 此架構包含向量索引編製和查詢的設定,以及語意排名的設定。

  1. 在 Visual Studio Code 中,開啟您稍早建立的az-search-vector-quickstart.rest檔案。

  2. 在檔案中尋找程式 ### Create a new index 代碼區塊。 此區塊包含在搜尋服務上建立 hotels-vector-quickstart 索引的要求。

    ### Create a new index
    POST  {{baseUrl}}/indexes?api-version=2023-11-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{token}}
    
    {
        "name": "hotels-vector-quickstart",
        "fields": [
            {
                "name": "HotelId", 
                "type": "Edm.String",
                "searchable": false, 
                "filterable": true, 
                "retrievable": true, 
                "sortable": false, 
                "facetable": false,
                "key": true
            },
            {
                "name": "HotelName", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": false, 
                "retrievable": true, 
                "sortable": true, 
                "facetable": false
            },
            {
                "name": "HotelNameVector",
                "type": "Collection(Edm.Single)",
                "searchable": true,
                "retrievable": true,
                "dimensions": 1536,
                "vectorSearchProfile": "my-vector-profile"
            },
            {
                "name": "Description", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": false, 
                "retrievable": true, 
                "sortable": false, 
                "facetable": false
            },
            {
                "name": "DescriptionVector",
                "type": "Collection(Edm.Single)",
                "searchable": true,
                "retrievable": true,
                "dimensions": 1536,
                "vectorSearchProfile": "my-vector-profile"
            },
                    {
                "name": "Description_fr", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": false, 
                "retrievable": true, 
                "sortable": false, 
                "facetable": false,
                "analyzer": "en.microsoft"
            },
            {
                "name": "Description_frvector",
                "type": "Collection(Edm.Single)",
                "searchable": true,
                "retrievable": true,
                "dimensions": 1536,
                "vectorSearchProfile": "my-vector-profile"
            },
            {
                "name": "Category", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": true, 
                "retrievable": true, 
                "sortable": true, 
                "facetable": true
            },
            {
                "name": "Tags",
                "type": "Collection(Edm.String)",
                "searchable": true,
                "filterable": true,
                "retrievable": true,
                "sortable": false,
                "facetable": true
            },
                    {
                "name": "ParkingIncluded",
                "type": "Edm.Boolean",
                "searchable": false,
                "filterable": true,
                "retrievable": true,
                "sortable": true,
                "facetable": true
            },
            {
                "name": "LastRenovationDate",
                "type": "Edm.DateTimeOffset",
                "searchable": false,
                "filterable": true,
                "retrievable": true,
                "sortable": true,
                "facetable": true
            },
            {
                "name": "Rating",
                "type": "Edm.Double",
                "searchable": false,
                "filterable": true,
                "retrievable": true,
                "sortable": true,
                "facetable": true
            },
            {
                "name": "Address", 
                "type": "Edm.ComplexType",
                "fields": [
                    {
                        "name": "StreetAddress", "type": "Edm.String",
                        "searchable": true, "filterable": false, "retrievable": true, "sortable": false, "facetable": false
                    },
                    {
                        "name": "City", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    },
                    {
                        "name": "StateProvince", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    },
                    {
                        "name": "PostalCode", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    },
                    {
                        "name": "Country", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    }
                ]
            },
            {
                "name": "Location",
                "type": "Edm.GeographyPoint",
                "searchable": false, 
                "filterable": true, 
                "retrievable": true, 
                "sortable": true, 
                "facetable": false
            }
        ],
        "vectorSearch": {
            "algorithms": [
                {
                    "name": "my-hnsw-vector-config-1",
                    "kind": "hnsw",
                    "hnswParameters": 
                    {
                        "m": 4,
                        "efConstruction": 400,
                        "efSearch": 500,
                        "metric": "cosine"
                    }
                },
                {
                    "name": "my-hnsw-vector-config-2",
                    "kind": "hnsw",
                    "hnswParameters": 
                    {
                        "m": 4,
                        "metric": "euclidean"
                    }
                },
                {
                    "name": "my-eknn-vector-config",
                    "kind": "exhaustiveKnn",
                    "exhaustiveKnnParameters": 
                    {
                        "metric": "cosine"
                    }
                }
            ],
            "profiles": [      
                {
                    "name": "my-vector-profile",
                    "algorithm": "my-hnsw-vector-config-1"
                }
          ]
        },
        "semantic": {
            "configurations": [
                {
                    "name": "my-semantic-config",
                    "prioritizedFields": {
                        "titleField": {
                            "fieldName": "HotelName"
                        },
                        "prioritizedContentFields": [
                            { "fieldName": "Description" }
                        ],
                        "prioritizedKeywordsFields": [
                            { "fieldName": "Category" }
                        ]
                    }
                }
            ]
        }
    }
    
  3. 選取 [傳送要求]。 您應該會有 HTTP/1.1 201 Created 回應。

回應主體應該包含索引架構的 JSON 表示法。

{
    "@odata.context": "https://my-demo-search.search.windows.net/$metadata#indexes/$entity",
    "@odata.etag": "\"0x8DD2E70E6C36D8E\"",
    "name": "hotels-vector-quickstart",
    "defaultScoringProfile": null,
    "fields": [
    {
        "name": "HotelId",
        "type": "Edm.String",
        "searchable": false,
        "filterable": true,
        "retrievable": true,
        "sortable": false,
        "facetable": false,
        "key": true,
        "indexAnalyzer": null,
        "searchAnalyzer": null,
        "analyzer": null,
        "dimensions": null,
        "vectorSearchProfile": null,
        "synonymMaps": []
    },
    [MORE FIELD DEFINITIONS OMITTED FOR BREVITY]
    ],
    "scoringProfiles": [],
    "corsOptions": null,
    "suggesters": [],
    "analyzers": [],
    "tokenizers": [],
    "tokenFilters": [],
    "charFilters": [],
    "encryptionKey": null,
    "similarity": {
    "@odata.type": "#Microsoft.Azure.Search.BM25Similarity",
    "k1": null,
    "b": null
    },
    "vectorSearch": {
    "algorithms": [
        {
        "name": "my-hnsw-vector-config-1",
        "kind": "hnsw",
        "hnswParameters": {
            "metric": "cosine",
            "m": 4,
            "efConstruction": 400,
            "efSearch": 500
        },
        "exhaustiveKnnParameters": null
        },
        {
        "name": "my-hnsw-vector-config-2",
        "kind": "hnsw",
        "hnswParameters": {
            "metric": "euclidean",
            "m": 4,
            "efConstruction": 400,
            "efSearch": 500
        },
        "exhaustiveKnnParameters": null
        },
        {
        "name": "my-eknn-vector-config",
        "kind": "exhaustiveKnn",
        "hnswParameters": null,
        "exhaustiveKnnParameters": {
            "metric": "cosine"
        }
        }
    ],
    "profiles": [
        {
        "name": "my-vector-profile",
        "algorithm": "my-hnsw-vector-config-1"
        }
    ]
    },
    "semantic": {
    "defaultConfiguration": null,
    "configurations": [
        {
        "name": "my-semantic-config",
        "prioritizedFields": {
            "titleField": {
            "fieldName": "HotelName"
            },
            "prioritizedContentFields": [
            {
                "fieldName": "Description"
            }
            ],
            "prioritizedKeywordsFields": [
            {
                "fieldName": "Category"
            }
            ]
        }
        }
    ]
    }
}

關於 建立索引 REST API 的重要內容:

  • fields 集合包含文字和向量搜尋所需的索引鍵欄位、文字和向量欄位(例如 DescriptionDescriptionVector)。 在同一個索引中共置向量和非向量欄位可啟用混合式查詢。 例如,您可以將篩選、文字搜尋與語意排名和向量合併成單一查詢作業。

  • 向量欄位必須是有 dimensionsvectorSearchProfile 屬性的 type: Collection(Edm.Single)

  • vectorSearch 區段是近似最近鄰演算法設定和設定檔的陣列。 支援的演算法包括階層式可導覽小世界 (navigable small world) 和詳盡的 K 最近鄰 (k-nearest neighbor)。 如需詳細資訊,請參閱向量搜尋中的相關性評分

  • (選擇性) semantic 組態可讓您重新檢閱搜尋結果。 針對設定中所指定的字串欄位,您可以進行類型 semantic 查詢結果的重新排名。 若要深入了解,請參閱語意排名概觀

上傳文件

建立和載入索引是單獨的步驟。 您在上一個步驟中建立了索引架構。 現在您需要將檔案載入索引中。

在 Azure AI 搜尋服務中,索引包含所有可搜尋資料以及對搜尋服務執行的查詢。 針對 REST 呼叫,數據會以 JSON 文件的形式提供。 針對這項工作使用 Documents- Index REST API。 URI 會擴充以包含 docs 集合和 index 作業。

  1. 在 Visual Studio Code 中,開啟您稍早建立的az-search-vector-quickstart.rest檔案。

  2. 在檔案中尋找程式 ### Upload documents 代碼區塊。 此區塊包含將檔上傳至 hotels-vector-quickstart 搜尋服務索引的要求。

    ### Upload documents
    POST {{baseUrl}}/indexes/hotels-quickstart-vectors/docs/index?api-version=2023-11-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{token}}
    
    {
        "value": [
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "1",
                "HotelName": "Stay-Kay City Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "The hotel is ideally located on the main commercial artery of the city 
                    in the heart of New York.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "pool",
                    "air conditioning",
                    "concierge"
                ],
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "2",
                "HotelName": "Old Century Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "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.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "pool",
                    "air conditioning",
                    "free wifi",
                    "concierge"
                ]
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "3",
                "HotelName": "Gastronomic Landscape Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "The Hotel stands out for its gastronomic excellence under the management of 
                    William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Resort and Spa",
                "Tags": [
                    "air conditioning",
                    "bar",
                    "continental breakfast"
                ]
            }
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "4",
                "HotelName": "Sublime Palace Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Sublime Palace 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 Palace is part of a lovingly restored 1800 palace.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "concierge",
                    "view",
                    "24-hour front desk service"
                ]
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "13",
                "HotelName": "Luxury Lion Resort",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury 
                    accommodations. Moments from the stadium, we feature the best in comfort",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Resort and Spa",
                "Tags": [
                    "view",
                    "free wifi",
                    "pool"
                ]
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "48",
                "HotelName": "Nordick's Valley Motel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Only 90 miles (about 2 hours) from the nation's capital and nearby 
                    most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring 
                    the caverns?  It's all nearby and we have specially priced packages to help make 
                    our B&B your home base for fun while visiting the valley.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "continental breakfast",
                    "air conditioning",
                    "free wifi"
                ],
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "49",
                "HotelName": "Swirling Currents Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Spacious rooms, glamorous suites and residences, rooftop pool, walking 
                    access to shopping, dining, entertainment and the city center.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Luxury",
                "Tags": [
                    "air conditioning",
                    "laundry service",
                    "24-hour front desk service"
                ]
            }
        ]
    }
    

    重要

    此範例中的程式代碼無法執行。 為了簡潔起見,會移除數個字元或幾行。 使用檔案 az-search-vector-quickstart.rest 中的程式代碼來執行要求。

  3. 選取 [傳送要求]。 您應該會有 HTTP/1.1 200 OK 回應。 回應本文應包含搜尋檔的 JSON 表示法。

檔案的重要 內容 - 索引 REST API 要求:

  • 承載中的文件是由索引架構中定義的欄位所組成。

  • 向量欄位包含浮點值。 維度屬性至少有 2 個,而且每個值最多 3,072 個浮點數。 本快速入門會將維度屬性設定為 1,536,因為這是 Azure OpenAI text-embedding-ada-002 模型所產生的內嵌大小。

執行查詢

現在已載入文件,您可以使用文件 - 搜尋貼文 (REST) 來對其發出向量查詢。

在下一節中,我們會對 hotels-vector-quickstart 索引執行查詢。 查詢包括:

範例向量查詢是以兩個字串為基礎:

  • 搜尋字串historic hotel walk to restaurants and shopping
  • 向量查詢字串 (向量化為數學表示法):classic lodging near running trails, eateries, retail

向量查詢字串在語意上類似於搜尋字串,但包含搜尋索引中不存在的字詞。 如果您對 classic lodging near running trails, eateries, retail 執行關鍵詞搜尋,則結果為零。 我們使用此範例示範如何取得相關結果,即使沒有相符的字詞也一樣。

  1. 在 Visual Studio Code 中,開啟您稍早建立的az-search-vector-quickstart.rest檔案。

  2. 在檔案中尋找程式 ### Run a single vector query 代碼區塊。 此區塊包含查詢搜尋索引的要求。

    ### Run a single vector query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
        {
            "count": true,
            "select": "HotelId, HotelName, Description, Category",
            "vectorQueries": [
                {
                    "vector"": [0.01944167, 0.0040178085
                        . . .  TRIMMED FOR BREVITY
                        010858015, -0.017496133],
                    "k": 7,
                    "fields": "DescriptionVector",
                    "kind": "vector",
                    "exhaustive": true
                }
            ]
        }
    

    為了簡潔起見,此向量查詢會縮短。 vectorQueries.vector 包含查詢輸入的向量化文字,fields 決定要搜尋的向量欄位,而 k 指定要傳回的最近鄰數目。

    向量查詢字串是 classic lodging near running trails, eateries, retail,其會向量化為此查詢的 1,536 個內嵌。

    重要

    此範例中的程式代碼無法執行。 為了簡潔起見,會移除數個字元或幾行。 使用檔案 az-search-vector-quickstart.rest 中的程式代碼來執行要求。

  3. 選取 [傳送要求]。 您應該會有 HTTP/1.1 200 OK 回應。 回應本文應包含搜尋結果的 JSON 表示法。

classic lodging near running trails, eateries, retail 對等向量的回應包含七個結果。 每個結果都會提供搜尋分數和列在 select 中的欄位。 在相似性搜尋中,回應一律包含依值相似度分數排序的 k 結果。

{
  "@odata.context": "https://my-demo-search.search.windows.net/indexes('hotels-vector-quickstart')/$metadata#docs(*)",
  "@odata.count": 7,
  "value": [
    {
      "@search.score": 0.85773647,
      "HotelId": "48",
      "HotelName": "Nordick's Motel",
      "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.8399132,
      "HotelId": "49",
      "HotelName": "Old Carrabelle Hotel",
      "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center.",
      "Category": "Luxury"
    },
    {
      "@search.score": 0.83839583,
      "HotelId": "13",
      "HotelName": "Historic Lion Resort",
      "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort",
      "Category": "Resort and Spa"
    },
    {
      "@search.score": 0.82543474,
      "HotelId": "4",
      "HotelName": "Sublime Cliff 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 1800 palace.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.82380104,
      "HotelId": "1",
      "HotelName": "Secret Point Hotel",
      "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.8151413,
      "HotelId": "2",
      "HotelName": "Twin Dome 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.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.8133767,
      "HotelId": "3",
      "HotelName": "Triple Landscape Hotel",
      "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel\u2019s restaurant services.",
      "Category": "Resort and Spa"
    }
  ]
}

使用篩選的單一向量搜尋

您可以新增篩選,但篩選條件會套用於索引中的非向量內容。 在此範例中,篩選會套用於 Tags 欄位,篩選排除任何不提供免費 Wi-Fi 的旅館。

  1. 在 Visual Studio Code 中,開啟您稍早建立的az-search-vector-quickstart.rest檔案。

  2. 在檔案中尋找程式 ### Run a vector query with a filter 代碼區塊。 此區塊包含查詢搜尋索引的要求。

    ### Run a vector query with a filter
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
        {
            "count": true,
            "select": "HotelId, HotelName, Category, Tags, Description",
            "filter": "Tags/any(tag: tag eq 'free wifi')",
            "vectorFilterMode": "postFilter",
            "vectorQueries": [
            {
                "vector": [ VECTOR OMITTED ],
                "k": 7,
                "fields": "DescriptionVector",
                "kind": "vector",
                "exhaustive": true
            },
        ]
    }
    

    重要

    此範例中的程式代碼無法執行。 為了簡潔起見,會移除數個字元或幾行。 使用檔案 az-search-vector-quickstart.rest 中的程式代碼來執行要求。

  3. 選取 [傳送要求]。 您應該會有 HTTP/1.1 200 OK 回應。 回應本文應包含搜尋結果的 JSON 表示法。

此查詢與前 一個單一向量搜尋範例相同,但它包含後置處理排除篩選條件,並只傳回具有免費Wi-Fi的三家酒店。

{
  "@odata.context": "https://my-demo-search.search.windows.net/indexes('hotels-vector-quickstart')/$metadata#docs(*)",
  "@odata.count": 3,
  "value": [
    {
      "@search.score": 0.85773647,
      "HotelId": "48",
      "HotelName": "Nordick's Motel",
      "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
      "Category": "Boutique",
      "Tags": [
        "continental breakfast",
        "air conditioning",
        "free wifi"
      ]
    },
    {
      "@search.score": 0.83839583,
      "HotelId": "13",
      "HotelName": "Historic Lion Resort",
      "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort",
      "Category": "Resort and Spa",
      "Tags": [
        "view",
        "free wifi",
        "pool"
      ]
    },
    {
      "@search.score": 0.8151413,
      "HotelId": "2",
      "HotelName": "Twin Dome 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.",
      "Category": "Boutique",
      "Tags": [
        "pool",
        "free wifi",
        "air conditioning",
        "concierge"
      ]
    }
  ]
}

混合式搜尋是由單一搜尋要求中的關鍵字查詢和向量查詢所組成。 此範例會同時執行向量查詢和全文檢索搜尋:

  • 搜尋字串historic hotel walk to restaurants and shopping
  • 向量查詢字串 (向量化為數學表示法):classic lodging near running trails, eateries, retail
  1. 在 Visual Studio Code 中,開啟您稍早建立的az-search-vector-quickstart.rest檔案。

  2. 在檔案中尋找程式 ### Run a hybrid query 代碼區塊。 此區塊包含查詢搜尋索引的要求。

    ### Run a hybrid query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
    {
        "count": true,
        "search": "historic hotel walk to restaurants and shopping",
        "select": "HotelName, Description",
        "top": 7,
        "vectorQueries": [
            {
                "vector": [ VECTOR OMITTED],
                "k": 7,
                "fields": "DescriptionVector",
                "kind": "vector",
                "exhaustive": true
            }
        ]
    }
    

    重要

    此範例中的程式代碼無法執行。 為了簡潔起見,會移除數個字元或幾行。 使用檔案 az-search-vector-quickstart.rest 中的程式代碼來執行要求。

  3. 選取 [傳送要求]。 您應該會有 HTTP/1.1 200 OK 回應。 回應本文應包含搜尋結果的 JSON 表示法。

因為這是混合式查詢,因此結果會依倒數排名融合 (RRF) 進行排名。 RRF 會評估多個搜尋結果的搜尋分數、採用反向排列,然後合併並排序合併的結果。 傳回的結果數目 top

檢閱回應:

{
    "@odata.count": 7,
    "value": [
        {
            "@search.score": 0.03279569745063782,
            "HotelName": "Luxury Lion Resort",
            "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort"
        },
        {
            "@search.score": 0.03226646035909653,
            "HotelName": "Sublime Palace Hotel",
            "Description": "Sublime Palace 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 Palace is part of a lovingly restored 1800 palace."
        },
        {
            "@search.score": 0.03226646035909653,
            "HotelName": "Swirling Currents Hotel",
            "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center."
        },
        {
            "@search.score": 0.03205128386616707,
            "HotelName": "Nordick's Valley Motel",
            "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley."
        },
        {
            "@search.score": 0.03128054738044739,
            "HotelName": "Gastronomic Landscape Hotel",
            "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services."
        },
        {
            "@search.score": 0.03100961446762085,
            "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."
        },
        {
            "@search.score": 0.03077651560306549,
            "HotelName": "Stay-Kay City Hotel",
            "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York."
        }
    ]
}

因為 RRF 會合併結果,所以有助於檢閱輸入。 下列結果僅來自全文檢索搜尋查詢。 前兩名的結果是崇高宮酒店和歷史獅子度假村。 昇華宮酒店具有更強的BM25相關性分數。

{
    "@search.score": 2.2626662,
    "HotelName": "Sublime Palace Hotel",
    "Description": "Sublime Palace 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 Palace is part of a lovingly restored 1800 palace."
},
{
    "@search.score": 0.86421645,
    "HotelName": "Luxury Lion Resort",
    "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort"
},

在僅向量查詢中,使用 HNSW 尋找相符專案,Sublime 故宮酒店會降至第四個位置。 Historic Lion 在全文檢索搜尋中排名第二,在向量搜尋中排名第三,並未經歷相同的波動範圍,因此成為同質化結果集中的最高相符項目。

"value": [
    {
        "@search.score": 0.857736,
        "HotelId": "48",
        "HotelName": "Nordick's Valley Motel",
        "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.8399129,
        "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.",
        "Category": "Luxury"
    },
    {
        "@search.score": 0.8383954,
        "HotelId": "13",
        "HotelName": "Luxury Lion Resort",
        "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort",
        "Category": "Resort and Spa"
    },
    {
        "@search.score": 0.8254346,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Palace 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 Palace is part of a lovingly restored 1800 palace.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.82380056,
        "HotelId": "1",
        "HotelName": "Stay-Kay City Hotel",
        "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.81514084,
        "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.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.8133763,
        "HotelId": "3",
        "HotelName": "Gastronomic Landscape Hotel",
        "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
        "Category": "Resort and Spa"
    }
]

使用篩選的語意混合式搜尋

以下是集合中的最後一個查詢。 此具有語意排名的混合式查詢會經過篩選,只顯示位於華盛頓特區 500 公里半徑內的旅館。您可以將 vectorFilterMode 設定為 null,這相當於預設值 (較新索引的 preFilter 和較舊索引的 postFilter)。

  1. 在 Visual Studio Code 中,開啟您稍早建立的az-search-vector-quickstart.rest檔案。

  2. 在檔案中尋找程式 ### Run a hybrid query with semantic reranking 代碼區塊。 此區塊包含查詢搜尋索引的要求。

    ### Run a hybrid query with semantic reranking
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
    {
        "count": true,
        "search": "historic hotel walk to restaurants and shopping",
        "select": "HotelId, HotelName, Category, Description,Address/City, Address/StateProvince",
        "filter": "geo.distance(Location, geography'POINT(-77.03241 38.90166)') le 500",
        "vectorFilterMode": null,
        "facets": [ "Address/StateProvince"],
        "top": 7,
        "queryType": "semantic",
        "answers": "extractive|count-3",
        "captions": "extractive|highlight-true",
        "semanticConfiguration": "my-semantic-config",
        "vectorQueries": [
            {
                "vector": [ VECTOR OMITTED ],
                "k": 7,
                "fields": "DescriptionVector",
                "kind": "vector",
                "exhaustive": true
            }
        ]
    }
    

    重要

    此範例中的程式代碼無法執行。 為了簡潔起見,會移除數個字元或幾行。 使用檔案 az-search-vector-quickstart.rest 中的程式代碼來執行要求。

  3. 選取 [傳送要求]。 您應該會有 HTTP/1.1 200 OK 回應。 回應本文應包含搜尋結果的 JSON 表示法。

檢閱回應。 回應中有三家旅館,依位置篩選,並根據 StateProvince 進行 Facet 篩選,然後經過語意排名以提升最接近搜尋字串查詢的結果 (historic hotel walk to restaurants and shopping)。

旋轉流酒店現在進入頂級位置。 沒有語意排名,北歐的山谷汽車旅館是頭號。 使用語意排名,機器理解模型認識到,historic 適用於「旅館,餐飲 (餐廳) 和購物地點在步行距離內」。

{
  "@odata.context": "https://my-demo-search.search.windows.net/indexes('hotels-vector-quickstart')/$metadata#docs(*)",
  "@odata.count": 2,
  "@search.facets": {
    "Address/StateProvince": [
      {
        "count": 1,
        "value": "VA"
      }
    ]
  },
  "@search.answers": [],
  "value": [
    {
      "@search.score": 0.03306011110544205,
      "@search.rerankerScore": 2.8773112297058105,
      "HotelId": "49",
      "HotelName": "Old Carrabelle Hotel",
      "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center.",
      "Category": "Luxury",
      "Address": {
        "City": "Arlington",
        "StateProvince": "VA"
      }
    },
    {
      "@search.score": 0.03306011110544205,
      "@search.rerankerScore": 2.1703834533691406,
      "HotelId": "48",
      "HotelName": "Nordick's Motel",
      "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
      "Category": "Boutique",
      "Address": {
        "City": "Washington D.C.",
        "StateProvince": null
      }
    }
  ]
}

檔案的重要 內容 - 搜尋 Post REST API:

  • 向量搜尋是透過 vectors.value 屬性來指定。 關鍵字搜尋是透過 search 屬性來指定。

  • 在混合式搜尋中,您可以將向量搜尋與關鍵字的全文檢索搜尋整合。 篩選、拼字檢查和語意排名僅適用於文字內容,而非向量。 在此最終查詢中,沒有語意 answer,因為系統不會產生足夠強的語意。

  • 實際結果包含更多詳細資料,包括語意標題和醒目提示。 結果已針對可讀性進行修改。 若要取得回應的完整結構,請在 REST 用戶端中執行要求。

清理

如果您是在自己的訂用帳戶中進行,建議您在專案結束時判斷自己是否仍需要先前所建立的資源。 資源若繼續執行,將需付費。 您可以個別刪除資源,或刪除資源群組以刪除整組資源。

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

如果您想要保留搜尋服務,但刪除索引和檔,您可以在 REST 用戶端中使用 DELETE 命令。 這個指令 (在 az-search-vector-quickstart.rest 檔案結尾處) 會 hotels-vector-quickstart 刪除索引:

### Delete an index
DELETE  {{baseUrl}}/indexes/hotels-vector-quickstart?api-version=2023-11-01 HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{token}}

下一步

在下一個步驟中,建議您瞭解如何在沒有 API 金鑰的情況下叫用 REST API 呼叫

您也可以檢閱 Python、C#JavaScript 的示範程式碼。