分享方式:


快速入門:使用 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. 選取 [設定]>[金鑰],然後取得服務之完整權限的管理金鑰。 您會取得兩個可互換的管理金鑰,以便在需要變換金鑰時保有商務持續性。 您可以在新增、修改及刪除物件的要求上使用主要或次要金鑰。

    顯示取得 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=2024-07-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 \(英文\)。

索引的必要元素包括名稱和欄位集合。 欄位集合會定義「文件」的結構。 每個欄位都有名稱、類型和用於決定其使用方式的屬性 (例如,該欄位是否可在搜尋結果中進行全文檢索搜尋、篩選或擷取)。 在索引內,類型為 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=2024-07-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 參數會指定索引的執行方式。 有效值包括 uploadmergemergeOrUploaddeletemergeOrUpload 行為會針對 hotelId = 3 建立新文件或更新內容 (如果文件已存在)。

    $body = @"
    {
        "value": [
        {
        "@search.action": "upload",
        "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. 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": "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",
        "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": "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",
        "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 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",
        "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 文件集合,並包含索引作業 (indexes/hotels-quickstart/docs/index)。

    $url = "https://<YOUR-SEARCH-SERVICE>.search.windows.net/indexes/hotels-quickstart/docs/index?api-version=2024-07-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. 將端點設定為 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=2024-07-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":  "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",
                      "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":  "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\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=2024-07-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=2024-07-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=2024-07-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=2024-07-01&search=pool&$orderby=Address/City asc&$select=HotelName, Address/City, Tags, Rating'

清除資源

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

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

如果您使用免費服務,請記住您會有三個索引、索引子和資料來源的限制。 您可以在入口網站中刪除個別項目,以避免超出限制。

下一步

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