快速入門:使用 REST API 在 PowerShell 中建立搜尋索引

在此 Azure AI 搜尋快速入門中,瞭解如何使用 PowerShell 和 Azure AI 搜尋 REST API 來建立、載入和 查詢搜尋索引。 本文說明如何以互動方式執行PowerShell命令。 或者,您可以 下載並執行執行相同作業的PowerShell腳本

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

必要條件

本快速入門需要下列服務和工具:

複製搜尋服務金鑰和 URL

在本快速入門中,REST 呼叫包含服務 URL 和每個要求的存取密鑰。 系統會使用這兩者來建立搜尋服務,因此如果您已將 Azure AI 搜尋新增至您的訂用帳戶,請遵循下列步驟來取得必要的資訊。

  1. 登入 Azure 入口網站。 在您的搜尋服務 [概觀] 頁面上,取得 URL。 範例端點看起來會像是 https://mydemo.search.windows.net

  2. 選取 [設定> Keys],然後取得服務完整許可權的管理密鑰。 如果您需要變換一個密鑰,則會提供兩個可交換的管理密鑰,以保持商務持續性。 您可以在新增、修改及刪除物件的要求上使用主要或次要金鑰。

    顯示取得 HTTP 端點和存取金鑰的螢幕快照。

所有要求都需要每個傳送至您服務的要求的 API 金鑰。 讓有效的密鑰在傳送要求與處理要求的服務之間,根據每個要求建立信任。

  1. 在 PowerShell 中,建立 $headers 物件來儲存內容類型和 API 金鑰。 將系統管理 API 金鑰 (YOUR-ADMIN-API-KEY) 取代為您搜尋服務有效的金鑰。 您只需要在會話期間設定此標頭一次,但您會將其新增至每個要求。

    $headers = @{
    'api-key' = '<YOUR-ADMIN-API-KEY>'
    'Content-Type' = 'application/json' 
    'Accept' = 'application/json' }
    
  2. 建立 $url 物件,指定服務的索引集合。 將服務名稱 (YOUR-SEARCH-SERVICE-NAME) 取代為有效的搜尋服務。

    $url = "https://<YOUR-SEARCH-SERVICE-NAME>.search.windows.net/indexes?api-version=2023-11-01&`$select=name"
    
  3. 執行 Invoke-RestMethod 以將 GET 要求傳送至服務,並驗證連線。 新增 ConvertTo-Json ,以便檢視從服務傳回的回應。

    Invoke-RestMethod -Uri $url -Headers $headers | ConvertTo-Json
    

    如果服務是空的,而且沒有索引,結果會類似下列範例。 否則,您會看到索引定義的 JSON 表示法。

    {
        "@odata.context":  "https://mydemo.search.windows.net/$metadata#indexes",
        "value":  [
    
                ]
    }
    

建立索引

除非您使用入口網站,否則服務上必須有索引,才能載入數據。 此步驟會定義索引,並將它推送至服務。 建立 索引 REST API 用於此步驟。

索引的必要元素包括名稱和 fields 集合。 fields 集合會定義文件的結構。 每個欄位都有名稱、類型和屬性,可決定其使用方式(例如,無論是全文搜索、可篩選或可在搜尋結果中擷取)。 在索引內,類型的 Edm.String 其中一個字段必須指定為 文件識別的索引鍵

此索引的名稱為 hotels-quickstart ,且具有您在下列程式代碼中看到的欄位定義。 這是其他逐步解說文章中使用的較大 旅館索引 子集。 本快速入門會修剪字段定義,以求簡潔。

  1. 將此範例貼到PowerShell中,以建立 $body 包含索引架構的物件。

    $body = @"
    {
        "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. 將 URI 設定為服務上的索引集合和 hotels-quickstart 索引。

    $url = "https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart?api-version=2023-11-01"
    
  3. 使用 $url$headers$body 執行 命令,以在服務上建立索引。

    Invoke-RestMethod -Uri $url -Headers $headers -Method Put -Body $body | ConvertTo-Json
    

    結果看起來應該類似這個範例,只顯示前兩個字段的簡潔性:

    {
        "@odata.context":  "https://mydemo.search.windows.net/$metadata#indexes/$entity",
        "@odata.etag":  "\"0x8D6EDE28CFEABDA\"",
        "name":  "hotels-quickstart",
        "defaultScoringProfile":  null,
        "fields":  [
                    {
                        "name":  "HotelId",
                        "type":  "Edm.String",
                        "searchable":  true,
                        "filterable":  true,
                        "retrievable":  true,
                        "sortable":  true,
                        "facetable":  true,
                        "key":  true,
                        "indexAnalyzer":  null,
                        "searchAnalyzer":  null,
                        "analyzer":  null,
                        "synonymMaps":  ""
                    },
                    {
                        "name":  "HotelName",
                        "type":  "Edm.String",
                        "searchable":  true,
                        "filterable":  false,
                        "retrievable":  true,
                        "sortable":  true,
                        "facetable":  false,
                        "key":  false,
                        "indexAnalyzer":  null,
                        "searchAnalyzer":  null,
                        "analyzer":  null,
                        "synonymMaps":  ""
                    },
                    . . .
        ]
    }
    

提示

如需驗證,您也可以檢查 入口網站中的 [索引 ] 清單。

載入文件

若要推送檔,請使用 HTTP POST 要求至索引的 URL 端點。 此工作的 REST API 為 [新增]、[更新] 或 [刪除檔]。

  1. 將此範例貼到 PowerShell 中,以建立 $body 包含您要上傳之文件的物件。

    此要求包含兩個完整記錄和一個部分記錄。 部分記錄示範您可以上傳不完整的檔。 參數 @search.action 會指定如何完成索引編製。 有效值包括 uploadmergemergeOrUploaddelete。 行為 mergeOrUpload 會為 hotelId = 3 建立新檔,或如果內容已經存在,則更新其內容。

    $body = @"
    {
        "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. 將端點設定為 hotels-quickstart docs 集合,並包含索引作業 (indexes/hotels-quickstart/docs/index)。

    $url = "https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs/index?api-version=2023-11-01"
    
  3. 使用 $url$headers$body 執行 命令,以將檔案 hotels-quickstart 載入索引中。

    Invoke-RestMethod -Uri $url -Headers $headers -Method Post -Body $body | ConvertTo-Json
    

    結果看起來應該類似下列範例。 您應該會看到 201 的狀態代碼。

    {
        "@odata.context":  "https://mydemo.search.windows.net/indexes(\u0027hotels-quickstart\u0027)/$metadata#Collection(Microsoft.Azure.Search.V2019_05_06.IndexResult)",
        "value":  [
                    {
                        "key":  "1",
                        "status":  true,
                        "errorMessage":  null,
                        "statusCode":  201
                    },
                    {
                        "key":  "2",
                        "status":  true,
                        "errorMessage":  null,
                        "statusCode":  201
                    },
                    {
                        "key":  "3",
                        "status":  true,
                        "errorMessage":  null,
                        "statusCode":  201
                    },
                    {
                        "key":  "4",
                        "status":  true,
                        "errorMessage":  null,
                        "statusCode":  201
                    }
                ]
    }
    

搜尋索引

此步驟說明如何使用搜尋檔 API 來查詢索引

請務必在搜尋 $urls上使用單引號。 查詢字串包含 $ 字元,如果整個字串以單引號括住,您可以省略必須逸出它們。

  1. 將端點設定為 docs 集合, hotels-quickstart 並新增 search 參數以傳入查詢字串。

    此字串會執行空的搜尋 (search=*),並傳回任意檔的未加入清單(搜尋分數 = 1.0)。 根據預設,Azure AI 搜尋會一次傳回 50 個相符專案。 如同結構化,此查詢會傳回整個文件結構和值。 新增 $count=true 以取得結果中所有文件的計數。

    $url = 'https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs?api-version=2023-11-01&search=*&$count=true'
    
  2. 執行 命令以將 傳送 $url 至服務。

    Invoke-RestMethod -Uri $url -Headers $headers | ConvertTo-Json
    

    結果看起來應該類似下列輸出:

    {
    "@odata.context":  "https://mydemo.search.windows.net/indexes(\u0027hotels-quickstart\u0027)/$metadata#docs(*)",
    "@odata.count":  4,
    "value":  [
                  {
                      "@search.score":  0.1547872,
                      "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.6,
                      "Address":  "@{StreetAddress=140 University Town Center Dr; City=Sarasota; StateProvince=FL; PostalCode=34243; Country=USA}"
                  },
                  {
                      "@search.score":  0.009068266,
                      "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\u0027s restaurant services.",
                      "Category":  "Resort and Spa",
                      "Tags":  "air conditioning bar continental breakfast",
                      "ParkingIncluded":  true,
                      "LastRenovationDate":  "2015-09-20T00:00:00Z",
                      "Rating":  4.8,
                      "Address":  "@{StreetAddress=3393 Peachtree Rd; City=Atlanta; StateProvince=GA; PostalCode=30326; Country=USA}"
                  },
                . . .
        ]
    }
    

請嘗試其他幾個查詢範例,以取得語法的感覺。 您可以執行字串搜尋、逐字 $filter 查詢、限制結果集、將搜尋範圍設定為特定欄位等等。

# Query example 1
# Search the entire index for the terms 'restaurant' and 'wifi'
# Return only the HotelName, Description, and Tags fields
$url = 'https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs?api-version=2023-11-01&search=restaurant wifi&$count=true&$select=HotelName,Description,Tags'

# Query example 2 
# Apply a filter to the index to find hotels rated 4 or higher
# Returns the HotelName and Rating. Two documents match.
$url = 'https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs?api-version=2023-11-01&search=*&$filter=Rating gt 4&$select=HotelName,Rating'

# Query example 3
# Take the top two results, and show only HotelName and Category in the results
$url = 'https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs?api-version=2023-11-01&search=boutique&$top=2&$select=HotelName,Category'

# Query example 4
# Sort by a specific field (Address/City) in ascending order

$url = 'https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs?api-version=2023-11-01&search=pool&$orderby=Address/City asc&$select=HotelName, Address/City, Tags, Rating'

清除資源

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

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

如果您使用免費服務,請記住,您僅限於三個索引、索引器和數據源。 您可以刪除入口網站中的個別專案,以維持在限制之下。

下一步

在本快速入門中,您已使用PowerShell逐步執行在 Azure AI 搜尋服務中建立和存取內容的基本工作流程。 考慮到概念,我們建議您繼續進行更進階的案例,例如從 Azure 數據源編製索引: