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

Azure AI 搜尋中的 REST API 可讓您以程式設計方式存取其所有功能,包括預覽功能,而且是瞭解功能運作方式的簡單方式。 在本快速入門中,瞭解如何呼叫 搜尋 REST API ,以在 Azure AI 搜尋服務中建立、載入及查詢搜尋索引。

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

必要條件

下載檔案

從 GitHub 下載 REST 範例 ,以在此快速入門中傳送要求。 如需詳細資訊,請參閱 從 GitHub 下載檔案。

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

複製搜尋服務金鑰和 URL

REST 呼叫需要每個要求的搜尋服務端點和 API 金鑰。 您可以從 Azure 入口網站 取得這些值。

  1. 登入 Azure 入口網站。 然後移至搜尋服務 [概觀 ] 頁面,並複製 URL。 範例端點看起來會像是 https://mydemo.search.windows.net

  2. 選取 [設定> Keys],然後複製管理密鑰。 管理員 索引鍵可用來新增、修改和刪除物件。 有兩個可交換的系統管理密鑰。 複製任一個。

    顯示 Azure 入口網站 中 URL 和 API 金鑰的螢幕快照。

設定 Visual Studio Code

如果您不熟悉 Visual Studio Code 的 REST 用戶端,本節會包含安裝程式,讓您可以完成本快速入門中的工作。

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

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

    顯示 [REST 用戶端安裝] 按鈕的螢幕快照。

  3. 以或 .http 擴展名開啟或建立名為 .rest 的新檔案。

  4. 貼上下列範例。 將基底 URL 和 API 金鑰取代為您稍早複製的值。

    @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. 選取 [傳送要求]。 回應應該會出現在相鄰窗格中。 如果您有現有的索引,則會列出它們。 否則,清單是空的。 如果 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
      api-key: {{apiKey}}
    
        {
            "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 用戶端螢幕快照。

關於索引定義

在索引架構中,fields 集合會定義文件結構。 您上傳的每個文件都必須具有這些欄位。 每個欄位都必須指派給 實體數據模型 (EDM) 數據類型。 字串欄位用於全文搜索。 如果您要讓數值資料可供搜尋,請確定資料類型為 Edm.String。 其他數據類型,例如 Edm.Int32 可篩選、可排序、可 Facet 和可擷取,但無法搜尋全文檢索。

欄位上的屬性會決定允許的動作。 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
      api-key: {{apiKey}}
    
        {
            "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
        api-key: {{apiKey}}
    
        {
            "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
      api-key: {{apiKey}}
    
  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 搜尋服務,請嘗試示範向量支援的另一個快速入門。