如何在 C# .NET 應用程式中使用 Azure.Search.Documents

本文說明如何使用適用於 .NET 的 Azure SDK 中的 C# 和 Azure.Search.Documents (第 11 版)客戶端連結庫來建立和管理搜尋物件。

關於第11版

適用於 .NET 的 Azure SDK 包含 來自 Azure SDK 小組的 Azure.Search.Documents 用戶端連結庫, 其功能相當於先前的用戶端連結庫 Microsoft.Azure.Search。 第 11 版在 Azure 程式設計方面更為一致。 一些範例包括 AzureKeyCredential 密鑰驗證,以及 JSON 串行化的 System.Text.Json.Serialization

如同舊版,您可以使用此連結庫來:

  • 建立和管理搜尋索引、數據源、索引器、技能集和同義字對應
  • 在索引中載入和管理搜尋檔
  • 執行查詢,完全不需要處理 HTTP 和 JSON 的詳細數據
  • 叫用和管理 AI 擴充 (技能集) 和輸出

連結庫會以單 一 Azure.Search.Documents NuGet 套件的形式散發,其中包含用來以程序設計方式存取搜尋服務的所有 API。

用戶端連結庫會定義類別,例如 SearchIndexSearchFieldSearchDocument,以及和類別上的 SearchIndexClientSearchClient 和等SearchIndexClient.CreateIndexSearchClient.Search作業。 這些類別會組織成下列命名空間:

Azure.Search.Documents(第 11 版)的目標是 2020-06-30 搜尋服務規格

用戶端連結庫不提供 服務管理作業,例如建立及調整搜尋服務及管理 API 密鑰。 如果您需要從 .NET 應用程式管理搜尋資源,請使用 Azure SDK for .NET 中的 Microsoft.Azure.Management.Search 連結 庫。

升級至 v11

如果您已使用舊版 .NET SDK,而且想要升級至目前正式運作的版本,請參閱 升級至 Azure AI 搜尋 .NET SDK 第 11 版。

SDK 需求

  • Visual Studio 2019 或更新版本。

  • 您自己的 Azure AI 搜尋服務。 若要使用 SDK,您需要服務的名稱和一或多個 API 金鑰。 如果您沒有服務,請在入口網站 中建立服務。

  • 使用 Visual Studio 中的工具>NuGet 封裝管理員> 管理適用於解決方案的 NuGet 套件,下載 Azure.Search.Documents 套件。 搜尋套件名稱 Azure.Search.Documents

適用於 .NET 的 Azure SDK 符合 .NET Standard 2.0

範例應用程式

本文「依範例教導」,依賴 GitHub 上的 DotNetHowTo 程式代碼範例來說明 Azure AI 搜尋中的基本概念,特別是如何建立、載入和查詢搜尋索引。

針對本文的其餘部分,假設名為 「hotels」 的新索引,並填入一些檔,其中包含數個符合結果的查詢。

以下是主要程序,顯示整體流程:

// This sample shows how to delete, create, upload documents and query an index
static void Main(string[] args)
{
    IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
    IConfigurationRoot configuration = builder.Build();

    SearchIndexClient indexClient = CreateSearchIndexClient(configuration);

    string indexName = configuration["SearchIndexName"];

    Console.WriteLine("{0}", "Deleting index...\n");
    DeleteIndexIfExists(indexName, indexClient);

    Console.WriteLine("{0}", "Creating index...\n");
    CreateIndex(indexName, indexClient);

    SearchClient searchClient = indexClient.GetSearchClient(indexName);

    Console.WriteLine("{0}", "Uploading documents...\n");
    UploadDocuments(searchClient);

    SearchClient indexClientForQueries = CreateSearchClientForQueries(indexName, configuration);

    Console.WriteLine("{0}", "Run queries...\n");
    RunQueries(indexClientForQueries);

    Console.WriteLine("{0}", "Complete.  Press any key to end application...\n");
    Console.ReadKey();
}

接下來是輸出的部分螢幕快照,假設您以有效的服務名稱和 API 金鑰執行此應用程式:

Screenshot of the Console.WriteLine output from the sample program.

用戶端類型

用戶端連結庫會針對各種作業使用三種用戶端類型: SearchIndexClient 建立、更新或刪除索引、 SearchClient 載入或查詢索引,以及 SearchIndexerClient 使用索引器和技能集。 本文著重於前兩個。

至少,所有用戶端都需要服務名稱或端點,以及 API 金鑰。 在組態檔中提供這項資訊很常見,類似於您在 DotNetHowTo 範例應用程式中找到appsettings.json的內容。 若要從組態檔讀取,請將 新增 using Microsoft.Extensions.Configuration; 至您的程式。

下列語句會建立用來建立、更新或刪除索引的索引用戶端。 它採用服務端點和系統管理 API 金鑰。

private static SearchIndexClient CreateSearchIndexClient(IConfigurationRoot configuration)
{
    string searchServiceEndPoint = configuration["SearchServiceEndPoint"];
    string adminApiKey = configuration["SearchServiceAdminApiKey"];

    SearchIndexClient indexClient = new SearchIndexClient(new Uri(searchServiceEndPoint), new AzureKeyCredential(adminApiKey));
    return indexClient;
}

下一個語句會建立用來載入檔或執行查詢的搜尋用戶端。 SearchClient 需要索引。 您需要系統管理員 API 金鑰才能載入檔,但您可以使用查詢 API 金鑰來執行查詢。

string indexName = configuration["SearchIndexName"];

private static SearchClient CreateSearchClientForQueries(string indexName, IConfigurationRoot configuration)
{
    string searchServiceEndPoint = configuration["SearchServiceEndPoint"];
    string queryApiKey = configuration["SearchServiceQueryApiKey"];

    SearchClient searchClient = new SearchClient(new Uri(searchServiceEndPoint), indexName, new AzureKeyCredential(queryApiKey));
    return searchClient;
}

注意

如果您為匯入作業提供無效的金鑰(例如,需要管理金鑰的查詢金鑰),將會 SearchClient 在第一次呼叫作業方法時擲回 CloudException 錯誤訊息「禁止」。 如果發生這種情況,請仔細檢查 API 金鑰。

刪除索引

在開發初期,您可能想要包含 DeleteIndex 語句來刪除進行中工作索引,以便使用更新的定義重新建立它。 Azure AI 搜尋的範例程式代碼通常包含刪除步驟,以便重新執行範例。

下列這行會呼叫 DeleteIndexIfExists

Console.WriteLine("{0}", "Deleting index...\n");
DeleteIndexIfExists(indexName, indexClient);

這個方法會使用指定的 SearchIndexClient 來檢查索引是否存在,如果是,則會將其刪除:

private static void DeleteIndexIfExists(string indexName, SearchIndexClient indexClient)
{
    try
    {
        if (indexClient.GetIndex(indexName) != null)
        {
            indexClient.DeleteIndex(indexName);
        }
    }
    catch (RequestFailedException e) when (e.Status == 404)
    {
        // Throw an exception if the index name isn't found
        Console.WriteLine("The index doesn't exist. No deletion occurred.");

注意

本文中的範例程式代碼為了簡單起見,會使用同步方法,但您應該在自己的應用程式中使用異步方法,讓它們保持可調整且回應。 例如,在上述方法中,您可以使用 DeleteIndexAsync 而不是 DeleteIndex

建立索引

您可以使用 SearchIndexClient 來建立索引。

下列方法會建立新的 SearchIndex 物件,其中包含定義新索引架構的物件清單 SearchField 。 每個欄位都有一個名稱、數據類型和數個屬性,可定義其搜尋行為。

您可以使用 從模型類別 FieldBuilder定義欄位。 類別FieldBuilder會藉由檢查指定Hotel模型類別的SearchField公用屬性和屬性,使用反映來建立索引的物件清單。 我們稍後會進一步了解課程 Hotel

private static void CreateIndex(string indexName, SearchIndexClient indexClient)
{
    FieldBuilder fieldBuilder = new FieldBuilder();
    var searchFields = fieldBuilder.Build(typeof(Hotel));

    var definition = new SearchIndex(indexName, searchFields);

    indexClient.CreateOrUpdateIndex(definition);
}

除了欄位,您也可以將評分配置檔、建議工具或 CORS 選項新增至索引(這些參數會從範例中省略,以求簡潔)。 您可以在屬性清單中,以及 REST API 參考中找到 SearchIndex SearchIndex 物件及其組成元件的詳細資訊。

注意

您隨時都可以直接建立物件清單 Field ,而不是視需要使用 FieldBuilder 。 例如,您可能不想使用模型類別,或者您可能需要使用您不想透過新增屬性來修改的現有模型類別。

在 Main 中呼叫 CreateIndex()

Main 呼叫上述方法,以建立新的 「hotels」 索引:

Console.WriteLine("{0}", "Creating index...\n");
CreateIndex(indexName, indexClient);

針對數據表示使用模型類別

DotNetHowTo 範例會針對 HotelAddressRoom 數據結構使用模型類別。 Hotel 參考 Address、單一層級複雜類型(多部分欄位)和 Room (多部分字段的集合)。

您可以使用這些類型來建立和載入索引,以及從查詢建構回應:

// Use-case: <Hotel> in a field definition
FieldBuilder fieldBuilder = new FieldBuilder();
var searchFields = fieldBuilder.Build(typeof(Hotel));

// Use-case: <Hotel> in a response
private static void WriteDocuments(SearchResults<Hotel> searchResults)
{
    foreach (SearchResult<Hotel> result in searchResults.GetResults())
    {
        Console.WriteLine(result.Document);
    }

    Console.WriteLine();
}

替代方法是直接將欄位新增至索引。 下列範例只會顯示幾個欄位。

 SearchIndex index = new SearchIndex(indexName)
 {
     Fields =
         {
             new SimpleField("hotelId", SearchFieldDataType.String) { IsKey = true, IsFilterable = true, IsSortable = true },
             new SearchableField("hotelName") { IsFilterable = true, IsSortable = true },
             new SearchableField("hotelCategory") { IsFilterable = true, IsSortable = true },
             new SimpleField("baseRate", SearchFieldDataType.Int32) { IsFilterable = true, IsSortable = true },
             new SimpleField("lastRenovationDate", SearchFieldDataType.DateTimeOffset) { IsFilterable = true, IsSortable = true }
         }
 };

欄位定義

.NET 中的數據模型及其對應的索引架構應該支援您想要提供給終端使用者的搜尋體驗。 .NET 中的每個最上層物件,例如搜尋索引中的搜尋檔,會對應至您在使用者介面中呈現的搜尋結果。 例如,在旅館搜尋應用程式中,使用者可能想要依旅館名稱、旅館功能或特定房間的特性來搜尋。

在每個類別中,欄位會以資料類型和屬性定義,以決定其使用方式。 每個類別中每個公用屬性的名稱會對應至索引定義中具有相同名稱的欄位。

請查看下列代碼段,從 Hotel 類別提取數個字段定義。 請注意,位址和會議室是具有其本身類別定義的 C# 類型(如果您想要檢視它們,請參閱範例程式代碼)。 兩者都是複雜類型。 如需詳細資訊,請參閱 如何建立複雜類型的模型。

public partial class Hotel
{
    [SimpleField(IsKey = true, IsFilterable = true)]
    public string HotelId { get; set; }

    [SearchableField(IsSortable = true)]
    public string HotelName { get; set; }

    [SearchableField(AnalyzerName = LexicalAnalyzerName.Values.EnLucene)]
    public string Description { get; set; }

    [SearchableField(IsFilterable = true, IsSortable = true, IsFacetable = true)]
    public string Category { get; set; }

    [JsonIgnore]
    public bool? SmokingAllowed => (Rooms != null) ? Array.Exists(Rooms, element => element.SmokingAllowed == true) : (bool?)null;

    [SearchableField]
    public Address Address { get; set; }

    public Room[] Rooms { get; set; }

選擇欄位類別

定義欄位時,您可以使用基 SearchField 類,也可以使用做為「範本」的衍生協助程式模型,以及預先設定的屬性。

索引中只有一個字段必須做為檔索引鍵 (IsKey = true)。 它必須是字串,而且必須唯一識別每個檔。 也需要有 IsHidden = true,這表示在搜尋結果中看不到。

欄位類型 描述和使用方式
SearchField 基類,其中大部分屬性都設定為 null,但必要屬性除外 Name ,而 AnalyzerName 預設為標準 Lucene。
SimpleField 協助程式模型。 可以是任何數據類型,一律不可搜尋(全文搜索查詢會忽略它),而且是可擷取的(它不會隱藏)。 其他屬性預設為關閉,但可以啟用。 您可以將 用於 SimpleField 文件識別碼或字段,只用於篩選、Facet 或評分配置檔。 如果是,請務必套用案例所需的任何屬性,例如 IsKey = true 文件標識符。 如需詳細資訊,請參閱 原始程式碼中的SimpleFieldAttribute.cs
SearchableField 協助程式模型。 必須是字串,且一律可搜尋且可擷取。 其他屬性預設為關閉,但可以啟用。 由於此欄位類型是可搜尋的,因此它支援同義字和分析器屬性的完整補充。 如需詳細資訊,請參閱 原始程式碼中的SearchableFieldAttribute.cs

無論您使用基本 SearchField API 還是其中一個協助程式模型,都必須明確啟用篩選、Facet 和排序屬性。 例如,IsFilterable、IsSortableIsFacetable 必須明確屬性化,如上述範例所示。

新增欄位屬性

請注意每個欄位如何裝飾屬性,例如 IsFilterableIsSortableIsKeyAnalyzerName。 這些屬性會直接對應至 Azure AI 搜尋索引中的對應欄位屬性。 類別 FieldBuilder 會使用這些屬性來建構索引的欄位定義。

欄位類型對應

屬性的 .NET 類型會對應至索引定義中的對等字段類型。 例如, Category 字串屬性會對應至 category 類型為 的 Edm.String欄位。 、Edm.BooleanDateTimeOffset?Edm.DateTimeOffset 之間有類似的型別對應bool?

您碰巧注意到 屬性 SmokingAllowed 嗎?

[JsonIgnore]
public bool? SmokingAllowed => (Rooms != null) ? Array.Exists(Rooms, element => element.SmokingAllowed == true) : (bool?)null;

JsonIgnore這個屬性上的 屬性會FieldBuilder告知 ,不要將它串行化為欄位的索引。 這是建立用戶端匯出屬性的絕佳方式,您可以在應用程式中做為協助程式使用。 在此情況下,屬性SmokingAllowed會反映集合中Rooms是否有任何Room允許吸煙。 如果都是假的,它表示整個酒店不允許吸煙。

載入索引

中的下一個步驟 Main 會填入新建立的「旅館」索引。 此索引母體擴展是在下列方法中完成的:(某些程序代碼已取代為 “...”為了說明目的。如需完整的數據母體擴展程序代碼,請參閱完整的範例解決方案。

private static void UploadDocuments(SearchClient searchClient)
{
    IndexDocumentsBatch<Hotel> batch = IndexDocumentsBatch.Create(
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "1",
                HotelName = "Secret Point Motel",
                ...
                Address = new Address()
                {
                    StreetAddress = "677 5th Ave",
                    ...
                },
                Rooms = new Room[]
                {
                    new Room()
                    {
                        Description = "Budget Room, 1 Queen Bed (Cityside)",
                        ...
                    },
                    new Room()
                    {
                        Description = "Budget Room, 1 King Bed (Mountain View)",
                        ...
                    },
                    new Room()
                    {
                        Description = "Deluxe Room, 2 Double Beds (City View)",
                        ...
                    }
                }
            }),
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "2",
                HotelName = "Twin Dome Motel",
                ...
                {
                    StreetAddress = "140 University Town Center Dr",
                    ...
                },
                Rooms = new Room[]
                {
                    new Room()
                    {
                        Description = "Suite, 2 Double Beds (Mountain View)",
                        ...
                    },
                    new Room()
                    {
                        Description = "Standard Room, 1 Queen Bed (City View)",
                        ...
                    },
                    new Room()
                    {
                        Description = "Budget Room, 1 King Bed (Waterfront View)",
                        ...
                    }
                }
            }),
        IndexDocumentsAction.Upload(
            new Hotel()
            {
                HotelId = "3",
                HotelName = "Triple Landscape Hotel",
                ...
                Address = new Address()
                {
                    StreetAddress = "3393 Peachtree Rd",
                    ...
                },
                Rooms = new Room[]
                {
                    new Room()
                    {
                        Description = "Standard Room, 2 Queen Beds (Amenities)",
                        ...
                    },
                    new Room ()
                    {
                        Description = "Standard Room, 2 Double Beds (Waterfront View)",
                        ...
                    },
                    new Room()
                    {
                        Description = "Deluxe Room, 2 Double Beds (Cityside)",
                        ...
                    }
                }
            }
        };

    try
    {
        IndexDocumentsResult result = searchClient.IndexDocuments(batch);
    }
    catch (Exception)
    {
        // Sometimes when your Search service is under load, indexing will fail for some of the documents in
        // the batch. Depending on your application, you can take compensating actions like delaying and
        // retrying. For this simple demo, we just log the failed document keys and continue.
        Console.WriteLine("Failed to index some of the documents: {0}");
    }

    Console.WriteLine("Waiting for documents to be indexed...\n");
    Thread.Sleep(2000);

這個方法有四個部分。 第一個會建立三個 對象的數位,每個物件都有三HotelRoom個物件,做為要上傳至索引的輸入數據。 為了簡單起見,此數據會硬式編碼。 在實際的應用程式中,數據可能來自外部數據源,例如 SQL 資料庫。

第二個部份會 IndexDocumentsBatch 建立包含檔案的 。 您可以藉由呼叫 IndexDocumentsAction.Upload來指定您想要在建立時套用至批次的作業。 然後,批次會透過 IndexDocuments 方法上傳至 Azure AI 搜尋服務索引。

注意

在此範例中,我們只是上傳檔。 如果您要將變更合併至現有的檔案或刪除檔,您可以改為呼叫 IndexDocumentsAction.MergeIndexDocumentsAction.MergeOrUploadIndexDocumentsAction.Delete 來建立批次。 您也可以藉由呼叫 IndexBatch.New來混合單一批次中的不同作業,其會採用 物件的集合 IndexDocumentsAction ,每個作業都會告訴 Azure AI 搜尋在文件上執行特定作業。 您可以藉由呼叫對應的方法,例如IndexDocumentsAction.MergeIndexAction.Upload等等,建立每個IndexDocumentsAction作業。

此方法的第三個部分是 catch 區塊,可處理索引編製的重要錯誤案例。 如果您的搜尋服務無法為批次中的某些檔案編制索引, RequestFailedException 則會擲回 。 如果您在服務負載過重時編製檔索引,就會發生例外狀況。 強烈建議您在程式代碼中明確處理此案例。 您可以延遲,然後重試編製失敗檔索引,或者您可以像範例一樣記錄並繼續,也可以根據應用程式的數據一致性需求執行其他動作。 替代方法是使用 SearchIndexingBufferedSender 進行智慧型手機批處理、自動排清,以及重試失敗的索引編製動作。 如需更多內容,請參閱 此範例

最後,方法 UploadDocuments 會延遲兩秒。 索引會在您的搜尋服務中以異步方式進行,因此範例應用程式需要等候一小段時間,以確保檔可供搜尋。 這類延遲通常只有在示範、測試和範例應用程式中才需要。

在 Main 中呼叫 UploadDocuments()

下列代碼段會使用 GetSearchClient indexClient 方法設定 的 實例SearchClient。 indexClient 會在其要求上使用系統管理 API 金鑰,這是載入或重新整理檔所需的密鑰。

替代方法是直接呼叫 SearchClient ,並在上 AzureKeyCredential傳入管理 API 金鑰。

SearchClient searchClient = indexClient.GetSearchClient(indexName);

Console.WriteLine("{0}", "Uploading documents...\n");
UploadDocuments(searchClient);

執行查詢

首先,設定 SearchClient ,從 appsettings.json讀取服務端點和查詢 API 金鑰:

private static SearchClient CreateSearchClientForQueries(string indexName, IConfigurationRoot configuration)
{
    string searchServiceEndPoint = configuration["SearchServiceEndPoint"];
    string queryApiKey = configuration["SearchServiceQueryApiKey"];

    SearchClient searchClient = new SearchClient(new Uri(searchServiceEndPoint), indexName, new AzureKeyCredential(queryApiKey));
    return searchClient;
}

其次,定義傳送查詢要求的方法。

每次方法執行查詢時,都會建立新的 SearchOptions 物件。 此物件可用來指定查詢的其他選項,例如排序、篩選、分頁和 Facet。 在此方法中,我們會為不同的查詢設定 FilterSelectOrderBy 屬性。 如需搜尋查詢表達式語法的詳細資訊, 請簡單查詢語法

下一個步驟是查詢執行。 執行搜尋是使用 SearchClient.Search 方法完成的。 針對每個查詢,傳遞要作為字串使用的搜尋文字(如果沒有 "*" 搜尋文字),加上稍早建立的搜尋選項。 我們也將 指定 Hotel 為的型別參數 SearchClient.Search,以告知 SDK 將搜尋結果中的檔還原串行化為 類型 Hotel的物件。

private static void RunQueries(SearchClient searchClient)
{
    SearchOptions options;
    SearchResults<Hotel> results;

    Console.WriteLine("Query 1: Search for 'motel'. Return only the HotelName in results:\n");

    options = new SearchOptions();
    options.Select.Add("HotelName");

    results = searchClient.Search<Hotel>("motel", options);

    WriteDocuments(results);

    Console.Write("Query 2: Apply a filter to find hotels with rooms cheaper than $100 per night, ");
    Console.WriteLine("returning the HotelId and Description:\n");

    options = new SearchOptions()
    {
        Filter = "Rooms/any(r: r/BaseRate lt 100)"
    };
    options.Select.Add("HotelId");
    options.Select.Add("Description");

    results = searchClient.Search<Hotel>("*", options);

    WriteDocuments(results);

    Console.Write("Query 3: Search the entire index, order by a specific field (lastRenovationDate) ");
    Console.Write("in descending order, take the top two results, and show only hotelName and ");
    Console.WriteLine("lastRenovationDate:\n");

    options =
        new SearchOptions()
        {
            Size = 2
        };
    options.OrderBy.Add("LastRenovationDate desc");
    options.Select.Add("HotelName");
    options.Select.Add("LastRenovationDate");

    results = searchClient.Search<Hotel>("*", options);

    WriteDocuments(results);

    Console.WriteLine("Query 4: Search the HotelName field for the term 'hotel':\n");

    options = new SearchOptions();
    options.SearchFields.Add("HotelName");

    //Adding details to select, because "Location" isn't supported yet when deserializing search result to "Hotel"
    options.Select.Add("HotelId");
    options.Select.Add("HotelName");
    options.Select.Add("Description");
    options.Select.Add("Category");
    options.Select.Add("Tags");
    options.Select.Add("ParkingIncluded");
    options.Select.Add("LastRenovationDate");
    options.Select.Add("Rating");
    options.Select.Add("Address");
    options.Select.Add("Rooms");

    results = searchClient.Search<Hotel>("hotel", options);

    WriteDocuments(results);
}

第三,定義將回應寫入的方法,將每個檔列印到主控台:

private static void WriteDocuments(SearchResults<Hotel> searchResults)
{
    foreach (SearchResult<Hotel> result in searchResults.GetResults())
    {
        Console.WriteLine(result.Document);
    }

    Console.WriteLine();
}

在 Main 中呼叫 RunQueries()

SearchClient indexClientForQueries = CreateSearchClientForQueries(indexName, configuration);

Console.WriteLine("{0}", "Running queries...\n");
RunQueries(indexClientForQueries);

探索查詢建構

讓我們仔細看看每個查詢。 以下是執行第一個查詢的程式代碼:

options = new SearchOptions();
options.Select.Add("HotelName");

results = searchClient.Search<Hotel>("motel", options);

WriteDocuments(results);

在此情況下,我們會在任何可搜尋的欄位中搜尋 「hotel」 這個字的整個索引,而我們只想要擷取選項所 Select 指定的旅館名稱。 以下是結果:

Name: Secret Point Motel

Name: Twin Dome Motel

在第二個查詢中,使用篩選條件來選取每晚費率小於 $100 的會議室。 只傳回結果中的旅館標識碼和描述:

options = new SearchOptions()
{
    Filter = "Rooms/any(r: r/BaseRate lt 100)"
};
options.Select.Add("HotelId");
options.Select.Add("Description");

results = searchClient.Search<Hotel>("*", options);

上述查詢會使用 OData $filter 運算式 Rooms/any(r: r/BaseRate lt 100)來篩選索引中的檔。 這會使用 任何運算符 ,將 『BaseRate lt 100』 套用至 Rooms 集合中的每個專案。 如需詳細資訊,請參閱 OData 篩選語法

在第三個查詢中,尋找最近裝修的前兩家酒店,並顯示酒店名稱和上次裝修日期。 程式碼如下:

options =
    new SearchOptions()
    {
        Size = 2
    };
options.OrderBy.Add("LastRenovationDate desc");
options.Select.Add("HotelName");
options.Select.Add("LastRenovationDate");

results = searchClient.Search<Hotel>("*", options);

WriteDocuments(results);

在最後一個查詢中,尋找符合 「hotel」 一字的所有旅館名稱:

options.Select.Add("HotelId");
options.Select.Add("HotelName");
options.Select.Add("Description");
options.Select.Add("Category");
options.Select.Add("Tags");
options.Select.Add("ParkingIncluded");
options.Select.Add("LastRenovationDate");
options.Select.Add("Rating");
options.Select.Add("Address");
options.Select.Add("Rooms");

results = searchClient.Search<Hotel>("hotel", options);

WriteDocuments(results);

本節總結了 .NET SDK 的簡介,但不會在此停止。 下一節會建議其他資源,以深入瞭解使用 Azure AI 搜尋進行程序設計。

下一步