共用方式為


快速入門:使用 REST 進行關鍵字搜尋

Azure AI 搜尋服務中的 REST API 可讓您以程式設計方式存取其所有功能 (包括預覽功能),而且能讓您輕鬆地了解功能的運作方式。 在本快速入門中,了解如何呼叫搜尋 REST API (部分機器翻譯),以在 Azure AI 搜尋服務中建立、載入及查詢搜尋索引。

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

必要條件

下載檔案

從 GitHub 下載 REST 範例 (英文),以在本快速入門中傳送要求。 如需相關指示,請參閱從 GitHub 下載檔案 (英文)。

您也可以使用本文中的指示,以手動方式在本機系統上開始新的檔案並建立要求。

取得搜尋服務端點

您可以在 Azure 入口網站中找到搜尋服務端點。

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

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

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

在稍後的步驟中,您會將此端點貼到 .rest.http 檔案中。

設定存取權

對搜尋端點發出的要求必須經過驗證和授權。 您可以針對這項工作使用 API 金鑰或角色。 金鑰較容易上手,但角色更安全。

針對角色型連線,下列指示可讓您連線到您身分識別 (不是用戶端應用程式的身分識別) 下的 Azure AI 搜尋服務。

選項 1:使用金鑰

選取 [設定]>[金鑰],然後複製系統管理金鑰。 系統管理金鑰可用來新增、修改和刪除物件。 有兩個可交換的系統管理密鑰。 複製任一個。 如需詳細資訊,請參閱使用金鑰驗證連線到 Azure AI 搜尋服務

顯示 Azure 入口網站中 API 金鑰的螢幕擷取畫面。

在稍後的步驟中,您會將此金鑰貼到 .rest.http 檔案中。

選項 2:使用角色

請確定您的搜尋服務已設定角色型存取。 您必須具備預先設定的開發人員存取角色指派。 您的角色指派必須授與建立、載入及查詢搜尋索引的權限。

在本節中,使用 Azure CLI、Azure PowerShell 或 Azure 入口網站取得您的個人身分識別權杖。

  1. 登入 Azure CLI。

    az login
    
  2. 取得您的個人身分識別權杖。

    az account get-access-token --scope https://search.azure.com/.default
    

您會在稍後的步驟中,將個人身分識別權杖貼到 .rest.http 檔案中。

注意

本節假設您使用的是代表您連線到 Azure AI 搜尋服務的本機用戶端。 替代方法是取得用戶端應用程式的權杖,並假設您的應用程式已註冊 Microsoft Entra ID。

設定 Visual Studio Code

如果您不熟悉 Visual Studio Code 的 REST 用戶端,本節包含設定方式,以便您可以完成本快速入門中的工作。

  1. 啟動 Visual Studio Code,然後選取 [延伸模組] 圖格。

  2. 搜尋 REST 用戶端,然後選取 [安裝]

    顯示 REST 用戶端 [安裝] 按鈕的螢幕擷取畫面。

  3. 開啟或建立以 .rest.http 副檔名命名的新檔案。

  4. 如果您使用 API 金鑰,請貼上下列範例。 將 @baseUrl@apiKey 預留位置取代為您稍早複製的值。

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-ENDPOINT-HERE
    @apiKey = PUT-YOUR-SEARCH-SERVICE-API-KEY-HERE
    
     ### List existing indexes by name
     GET  {{baseUrl}}/indexes?api-version=2023-11-01&$select=name  HTTP/1.1
       Content-Type: application/json
       api-key: {{apiKey}}
    
  5. 或者,如果您使用角色,請貼上此範例。 將 @baseUrl@token 預留位置取代為您稍早複製的值。

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-ENDPOINT-HERE
    @token = PUT-YOUR-PERSONAL-IDENTITY-TOKEN-HERE
    
     ### List existing indexes by name
     GET  {{baseUrl}}/indexes?api-version=2023-11-01&$select=name  HTTP/1.1
       Content-Type: application/json
       Authorization: Bearer {{token}}
    
  6. 選取 [傳送要求]。 回應應該會出現在相鄰窗格中。 如果您有現有的索引,窗格中便會列出。 否則,清單會是空的。 如果 HTTP 代碼為 200 OK,表示您已準備好進行後續步驟。

    此螢幕擷取畫面顯示針對搜尋服務要求所設定的 REST 用戶端。

    重點︰

    • 您可以使用 @ 前置詞來指定參數。
    • ### 會指定 REST 呼叫。 下一行包含要求,要求中必須包含 HTTP/1.1
    • Send request 應該會出現在要求之上。

建立索引

新增第二個要求到您的 .rest 檔案。 建立索引 (REST) (部分機器翻譯) 會建立搜尋索引,並在您的搜尋服務上設定實體資料結構。

  1. 貼上下列範例,在搜尋服務上建立 hotels-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-quickstart",  
            "fields": [
                {"name": "HotelId", "type": "Edm.String", "key": true, "filterable": true},
                {"name": "HotelName", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": true, "facetable": false},
                {"name": "Description", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": false, "facetable": false, "analyzer": "en.lucene"},
                {"name": "Category", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
                {"name": "Tags", "type": "Collection(Edm.String)", "searchable": true, "filterable": true, "sortable": false, "facetable": true},
                {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": true, "sortable": true, "facetable": true},
                {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": true, "sortable": true, "facetable": true},
                {"name": "Rating", "type": "Edm.Double", "filterable": true, "sortable": true, "facetable": true},
                {"name": "Address", "type": "Edm.ComplexType", 
                    "fields": [
                    {"name": "StreetAddress", "type": "Edm.String", "filterable": false, "sortable": false, "facetable": false, "searchable": true},
                    {"name": "City", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
                    {"name": "StateProvince", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
                    {"name": "PostalCode", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
                    {"name": "Country", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true}
                    ]
                }
            ]
        }
    
  2. 選取 [傳送要求]。 您應該會得到 HTTP/1.1 201 Created 回應,且回應本文中應該會包含以 JSON 表示的索引結構描述。

    如果您收到 Header name must be a valid HTTP token ["{"] 錯誤,請確定 api-key 與要求本文之間有空行。 如果您收到 HTTP 504,請驗證 URL 所指定的是 HTTPS。 如果您看見 HTTP 400 或 404,請查看要求本文以確認並沒有「複製-貼上」錯誤。 HTTP 403 通常表示 API 金鑰有問題。 不是金鑰無效,就是 API 金鑰的指定方式有語法方面的問題。

    現在,您的檔案中有數個要求。 回想一下,### 會啟動新的要求,而且每個要求都會獨立執行。

    顯示具有多個要求之 REST 用戶端的螢幕擷取畫面。

關於索引定義

在索引結構描述內,欄位集合會定義文件結構。 您上傳的每個文件都必須有這些欄位。 每個欄位都必須指派給實體資料模型 (EDM) 資料類型 (部分機器翻譯)。 在全文檢索搜尋中,會使用字串欄位。 如果您要讓數值資料可供搜尋,請確定資料類型為 Edm.String。 其他資料類型 (例如 Edm.Int32) 均可篩選、可排序、可面向化和可擷取,但無法全文檢索搜尋。

欄位上的屬性會決定允許的動作。 REST API 預設允許許多動作。 例如,預設所有字串都是可搜尋和擷取的。 針對 REST API,可能只有在需要關閉某一行為時,才需要使用屬性。

{
    "name": "hotels-quickstart",  
    "fields": [
        {"name": "HotelId", "type": "Edm.String", "key": true, "filterable": true},
        {"name": "HotelName", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": true, "facetable": false},
        {"name": "Description", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": false, "facetable": false, "analyzer": "en.lucene"},
        {"name": "Category", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
        {"name": "Tags", "type": "Collection(Edm.String)", "searchable": true, "filterable": true, "sortable": false, "facetable": true},
        {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": true, "sortable": true, "facetable": true},
        {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": true, "sortable": true, "facetable": true},
        {"name": "Rating", "type": "Edm.Double", "filterable": true, "sortable": true, "facetable": true},
        {"name": "Address", "type": "Edm.ComplexType", 
        "fields": [
        {"name": "StreetAddress", "type": "Edm.String", "filterable": false, "sortable": false, "facetable": false, "searchable": true},
        {"name": "City", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
        {"name": "StateProvince", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
        {"name": "PostalCode", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true},
        {"name": "Country", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true}
        ]
     }
  ]
}

載入文件

建立和載入索引是單獨的步驟。 在 Azure AI 搜尋服務中,索引包含所有可搜尋資料以及對搜尋服務執行的查詢。 針對 REST 呼叫,數據會以 JSON 文件的形式提供。 針對這項工作使用 Documents- Index REST API

我們已延長 URI 來加入 docs 集合和 index 作業。

  1. 貼上下列範例,將 JSON 文件上傳至搜尋索引。

    ### Upload documents
    POST {{baseUrl}}/indexes/hotels-quickstart/docs/index?api-version=2023-11-01  HTTP/1.1
      Content-Type: application/json
      Authorization: Bearer {{token}}
    
        {
            "value": [
            {
            "@search.action": "upload",
            "HotelId": "1",
            "HotelName": "Secret Point Motel",
            "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's 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.",
            "Category": "Boutique",
            "Tags": [ "pool", "air conditioning", "concierge" ],
            "ParkingIncluded": false,
            "LastRenovationDate": "1970-01-18T00:00:00Z",
            "Rating": 3.60,
            "Address": 
                {
                "StreetAddress": "677 5th Ave",
                "City": "New York",
                "StateProvince": "NY",
                "PostalCode": "10022",
                "Country": "USA"
                } 
            },
            {
            "@search.action": "upload",
            "HotelId": "2",
            "HotelName": "Twin Dome Motel",
            "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", "concierge" ],
            "ParkingIncluded": false,
            "LastRenovationDate": "1979-02-18T00:00:00Z",
            "Rating": 3.60,
            "Address": 
                {
                "StreetAddress": "140 University Town Center Dr",
                "City": "Sarasota",
                "StateProvince": "FL",
                "PostalCode": "34243",
                "Country": "USA"
                } 
            },
            {
            "@search.action": "upload",
            "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’s restaurant services.",
            "Category": "Resort and Spa",
            "Tags": [ "air conditioning", "bar", "continental breakfast" ],
            "ParkingIncluded": true,
            "LastRenovationDate": "2015-09-20T00:00:00Z",
            "Rating": 4.80,
            "Address": 
                {
                "StreetAddress": "3393 Peachtree Rd",
                "City": "Atlanta",
                "StateProvince": "GA",
                "PostalCode": "30326",
                "Country": "USA"
                } 
            },
            {
            "@search.action": "upload",
            "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",
            "Tags": [ "concierge", "view", "24-hour front desk service" ],
            "ParkingIncluded": true,
            "LastRenovationDate": "1960-02-06T00:00:00Z",
            "Rating": 4.60,
            "Address": 
                {
                "StreetAddress": "7400 San Pedro Ave",
                "City": "San Antonio",
                "StateProvince": "TX",
                "PostalCode": "78216",
                "Country": "USA"
                }
            }
          ]
        }
    
  2. 選取 [傳送要求]。 幾秒鐘後,您應該就會在相鄰窗格中看見 HTTP 201 回應。

    如果您收到 207,表示至少有一個文件上傳失敗。 如果您收到 404,則表示要求的標頭或本文有語法錯誤。 請驗證您已將端點變更為包含 /docs/index

執行查詢

現在已載入文件,您可以使用文件 - 搜尋貼文 (REST) (部分機器翻譯) 來對其發出查詢。

我們已延長 URI 來加入使用 /docs/search 運算子指定的查詢運算式。

  1. 貼上下列範例以查詢搜尋索引。 然後,選取 [傳送要求]。 文字搜尋要求一律會包含 search 參數。 此範例包含會將文字搜尋限制在特定欄位的選擇性 searchFields 參數。

    ### Run a query
    POST {{baseUrl}}/indexes/hotels-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
      Content-Type: application/json
      Authorization: Bearer {{token}}
    
      {
          "search": "lake view",
          "select": "HotelId, HotelName, Tags, Description",
          "searchFields": "Description, Tags",
          "count": true
      }
    
  2. 檢閱相鄰窗格中的回應。 您應該會有一個指出索引中所找到相符項目數目的計數、一個指出相關性的搜尋分數,以及 select 陳述式中所列各個欄位的值。

    {
      "@odata.context": "https://my-demo.search.windows.net/indexes('hotels-quickstart')/$metadata#docs(*)",
      "@odata.count": 1,
      "value": [
        {
          "@search.score": 0.6189728,
          "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.",
          "Tags": [
            "concierge",
            "view",
            "24-hour front desk service"
          ]
        }
      ]
    }
    

取得索引屬性

您也可以使用取得統計資料來查詢文件計數和索引大小。

  1. 貼上下列範例以查詢搜尋索引。 然後,選取 [傳送要求]

    ### Get index statistics
    GET {{baseUrl}}/indexes/hotels-quickstart/stats?api-version=2023-11-01  HTTP/1.1
      Content-Type: application/json
      Authorization: Bearer {{token}}
    
  2. 檢閱回應。 這項作業可讓您輕鬆地取得索引儲存體的詳細資料。

    {
      "@odata.context": "https://my-demo.search.windows.net/$metadata#Microsoft.Azure.Search.V2023_11_01.IndexStatistics",
      "documentCount": 4,
      "storageSize": 34707,
      "vectorIndexSize": 0
    }
    

清除資源

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

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

您也可以嘗試此 DELETE 命令:

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

後續步驟

現在您已熟悉 REST 用戶端並對 Azure AI 搜尋服務發出 REST 呼叫,接下來請嘗試另一個會示範向量支援的快速入門。