升级到 Azure 认知搜索 .NET SDK 版本 11Upgrade to Azure Cognitive Search .NET SDK version 11

如果你使用的是 10.0 或更低版本的 .NET SDK,则本文可帮助你升级到版本 11。If you're using version 10.0 or older of the .NET SDK, this article will help you upgrade to version 11.

版本 11 是完全重新设计的客户端库,由 Azure SDK 开发团队发布(以前的版本由 Azure 认知搜索开发团队生成)。Version 11 is a fully redesigned client library, released by the Azure SDK development team (previous versions were produced by the Azure Cognitive Search development team). 已对该库进行了重新设计,使其与其他 Azure 客户端库更加一致,依赖于 Azure.CoreSystem.Text.Json,并为常见任务实现了熟悉的方法。The library has been redesigned for greater consistency with other Azure client libraries, taking a dependency on Azure.Core and System.Text.Json, and implementing familiar approaches for common tasks.

新版本中的一些主要区别包括:Some key differences you'll notice in the new version include:

  • 一个包和库,而不是多个One package and library as opposed to multiple
  • 新包名称是 Azure.Search.Documents,而不是 Microsoft.Azure.SearchA new package name: Azure.Search.Documents instead of Microsoft.Azure.Search.
  • 三个客户端(而不是两个):SearchClientSearchIndexClientSearchIndexerClientThree clients instead of two: SearchClient, SearchIndexClient, SearchIndexerClient
  • 一系列 API 的命名差异,以及简化了某些任务的小的结构差异Naming differences across a range of APIs and small structural differences that simplify some tasks

备注

有关 .NET SDK 版本 11 中的变更的详细列表,请查看 更改日志Review the change log for an itemized list of changes in .NET SDK version 11.

包和库合并Package and library consolidation

版本 11 将多个包和库合并成了一个。Version 11 consolidates multiple packages and libraries into one. 迁移后,需要管理的库较少。Post-migration, you will have fewer libraries to manage.

客户端差异Client differences

下表映射了两个版本的客户端库(适用情况下)。Where applicable, the following table maps the client libraries between the two versions.

操作作用域Scope of operations Microsoft.Azure.Search (v10)Microsoft.Azure.Search (v10) Azure.Search.Documents (v11)Azure.Search.Documents (v11)
用于查询以及用于填充索引的客户端。Client used for queries and to populate an index. SearchIndexClientSearchIndexClient SearchClientSearchClient
用于索引、分析器、同义词映射的客户端Client used for indexes, analyzers, synonym maps SearchServiceClientSearchServiceClient SearchIndexClientSearchIndexClient
用于索引器、数据源、技能组的客户端Client used for indexers, data sources, skillsets SearchServiceClientSearchServiceClient SearchIndexerClient(新增SearchIndexerClient (new)

重要

SearchIndexClient 在两个版本中均存在,但支持不同的功能。SearchIndexClient exists in both versions, but supports different things. 在版本 10 中,SearchIndexClient 创建索引和其他对象。In version 10, SearchIndexClient create indexes and other objects. 在版本 11 中,SearchIndexClient 处理现有索引。In version 11, SearchIndexClient works with existing indexes. 为了避免在更新代码时产生混淆,请注意更新客户端引用时的顺序。To avoid confusion when updating code, be mindful of the order in which client references are updated. 按照升级步骤中的顺序进行操作应当有助于缓解任何字符串替换问题。Following the sequence in Steps to upgrade should help mitigate any string replacement issues.

命名和其他 API 差异Naming and other API differences

除了客户端差异以外(前面已提到,因此在此处省略),还重命名了多个其他 API,在某些情况下对其进行了重新设计。Besides the client differences (noted previously and thus omitted here), multiple other APIs have been renamed and in some cases redesigned. 下面汇总了类名称差异。Class name differences are summarized below. 此列表并非详尽无遗,但它确实按任务将 API 更改进行了分组,这对于特定代码块的修订很有帮助。This list is not exhaustive but it does group API changes by task, which can be helpful for revisions on specific code blocks. 有关 API 更新的详细列表,请参阅 GitHub 上 Azure.Search.Documents更改日志For an itemized list of API updates, see the change log for Azure.Search.Documents on GitHub.

身份验证和加密Authentication and encryption

版本 10Version 10 版本 11 等效项Version 11 equivalent
SearchCredentialsSearchCredentials AzureKeyCredentialAzureKeyCredential
EncryptionKey(已作为正式版功能存在于预览版 SDK 中)EncryptionKey (existed in the preview SDK as a generally available feature) SearchResourceEncryptionKeySearchResourceEncryptionKey

索引、分析器、同义词映射Indexes, analyzers, synonym maps

版本 10Version 10 版本 11 等效项Version 11 equivalent
IndexIndex SearchIndexSearchIndex
字段Field SearchFieldSearchField
DataTypeDataType SearchFieldDataTypeSearchFieldDataType
ItemErrorItemError SearchIndexerErrorSearchIndexerError
AnalyzerAnalyzer LexicalAnalyzer(另外,AnalyzerName 对应于 LexicalAnalyzerNameLexicalAnalyzer (also, AnalyzerName to LexicalAnalyzerName)
AnalyzeRequestAnalyzeRequest AnalyzeTextOptionsAnalyzeTextOptions
StandardAnalyzerStandardAnalyzer LuceneStandardAnalyzerLuceneStandardAnalyzer
StandardTokenizerStandardTokenizer LuceneStandardTokenizer(另外,StandardTokenizerV2 对应于 LuceneStandardTokenizerV2LuceneStandardTokenizer (also, StandardTokenizerV2 to LuceneStandardTokenizerV2)
TokenInfoTokenInfo AnalyzedTokenInfoAnalyzedTokenInfo
分词器Tokenizer LexicalTokenizer(另外,TokenizerName 对应于 LexicalTokenizerNameLexicalTokenizer (also, TokenizerName to LexicalTokenizerName)
SynonymMap.FormatSynonymMap.Format 无。None. 删除了对 Format 的引用。Remove references to Format.

简化了字段定义:SearchableFieldSimpleFieldComplexField 是用于创建字段定义的新 API。Field definitions are streamlined: SearchableField, SimpleField, ComplexField are new APIs for creating field definitions.

索引器、数据源、技能组Indexers, datasources, skillsets

版本 10Version 10 版本 11 等效项Version 11 equivalent
索引器Indexer SearchIndexerSearchIndexer
DataSourceDataSource SearchIndexerDataSourceConnectionSearchIndexerDataSourceConnection
SkillSkill SearchIndexerSkillSearchIndexerSkill
技能集Skillset SearchIndexerSkillsetSearchIndexerSkillset
DataSourceTypeDataSourceType SearchIndexerDataSourceTypeSearchIndexerDataSourceType

数据导入Data import

版本 10Version 10 版本 11 等效项Version 11 equivalent
IndexActionIndexAction IndexDocumentsActionIndexDocumentsAction
IndexBatchIndexBatch IndexDocumentsBatchIndexDocumentsBatch

查询定义和结果Query definitions and results

版本 10Version 10 版本 11 等效项Version 11 equivalent
DocumentSearchResultDocumentSearchResult SearchResultSearchResults,具体取决于结果是单个文档还是多个文档。SearchResult or SearchResults, depending on whether the result is a single document or multiple.
DocumentSuggestResultDocumentSuggestResult SuggestResultsSuggestResults
SearchParametersSearchParameters SearchOptionsSearchOptions

版本 11 中的功能What's in version 11

Azure 认知搜索客户端库的每个版本都面向 REST API 的一个对应版本。Each version of an Azure Cognitive Search client library targets a corresponding version of the REST API. REST API 被视为服务的基础,而各个 SDK 用于包装 REST API 的版本。The REST API is considered foundational to the service, with individual SDKs wrapping a version of the REST API. 作为 .NET 开发人员,如果想要了解有关特定对象或操作的更多背景知识,查看 REST API 文档会很有帮助。As a .NET developer, it can be helpful to review REST API documentation if you want more background on specific objects or operations.

版本 11 对应于 2020-06-30 搜索服务Version 11 targets the 2020-06-30 search service. 因为版本 11 也是从头开始构建的新客户端库,所以大部分开发工作都集中在与版本 10 的等效性上,一些 REST API 功能支持尚待提供。Because version 11 is also a new client library built from the ground up, most of the development effort has focused on equivalency with version 10, with some REST API feature support still pending.

版本 11.0 完全支持以下对象和操作:Version 11.0 fully supports the following objects and operations:

  • 索引创建和管理Index creation and management
  • 同义词映射创建和管理Synonym map creation and management
  • 所有查询类型和语法(地理空间筛选器除外)All query types and syntax (except geo-spatial filters)
  • 用于为 Azure 数据源(包括数据源和技能组)编制索引的索引器对象和操作Indexer objects and operations for indexing Azure data sources, including data sources and skillsets

版本 11.1 添加了以下项:Version 11.1 adds the following:

待解决功能Pending features

版本 10 中的以下功能在版本 11 中尚不可用。The following version 10 features are not yet available in version 11. 如果需要这些功能,请推迟迁移,直到这些功能受支持。If you require these features, hold off on migration until they are supported.

升级步骤Steps to upgrade

以下步骤通过遍历第一组必需任务(特别是在客户端引用方面)开始执行代码迁移。The following steps get you started on a code migration by walking through the first set of required tasks, especially in regards to client references.

  1. 在 Visual Studio 中,右键单击你的项目引用并选择“管理 NuGet 包...”,以安装 Azure.Search.Documents 包Install the Azure.Search.Documents package by right-clicking on your project references and selecting "Manage NuGet Packages..." in Visual Studio.

  2. 将用于 Microsoft.Azure.Search 的 using 指令替换为以下项:Replace using directives for Microsoft.Azure.Search with the following:

    using Azure;
    using Azure.Search.Documents;
    using Azure.Search.Documents.Indexes;
    using Azure.Search.Documents.Indexes.Models;
    using Azure.Search.Documents.Models;
    
  3. 对于需要 JSON 序列化的类,请将 using Newtonsoft.Json 替换为 using System.Text.Json.SerializationFor classes that require JSON serialization, replace using Newtonsoft.Json with using System.Text.Json.Serialization.

  4. 修订客户端身份验证代码。Revise client authentication code. 在以前的版本中,你会使用客户端对象上的属性(例如,SearchServiceClient.Credentials 属性)设置 API 密钥。In previous versions, you would use properties on the client object to set the API key (for example, the SearchServiceClient.Credentials property). 在当前版本中,请使用 AzureKeyCredential 类将密钥作为凭据传递,以便在需要时可以更新 API 密钥,而无需创建新的客户端对象。In the current version, use the AzureKeyCredential class to pass the key as a credential, so that if needed, you can update the API key without creating new client objects.

    客户端属性已精简,仅剩 EndpointServiceNameIndexName(如果适用)。Client properties have been streamlined to just Endpoint, ServiceName, and IndexName (where appropriate). 下面的示例使用系统 Uri 类提供终结点,并使用 Environment 类来读取密钥值:The following example uses the system Uri class to provide the endpoint and the Environment class to read in the key value:

    Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
    AzureKeyCredential credential = new AzureKeyCredential(
       Environment.GetEnvironmentVariable("SEARCH_API_KEY"));
    SearchIndexClient indexClient = new SearchIndexClient(endpoint, credential);
    
  5. 为索引器相关对象添加新的客户端引用。Add new client references for indexer-related objects. 如果使用的是索引器、数据源或技能组,请将客户端引用更改为 SearchIndexerClientIf you are using indexers, datasources, or skillsets, change the client references to SearchIndexerClient. 此客户端是版本 11 中的新客户端,之前没有。This client is new in version 11 and has no antecedent.

  6. 重新访问集合。Revisit collections. 在新的 SDK 中,所有列表都是只读的,这是为了避免在列表刚好包含 NULL 值时出现下游问题。In the new SDK, all lists are read-only to avoid downstream issues if the list happens to contain null values. 代码更改是为了向列表中添加项。The code change is to add items to a list. 例如,可以按如下所示添加字符串,而不是为 Select 属性指定字符串:For example, instead of assigning strings to a Select property, you would add them as follows:

    var options = new SearchOptions
     {
        SearchMode = SearchMode.All,
        IncludeTotalCount = true
     };
    
     // Select fields to return in results.
     options.Select.Add("HotelName");
     options.Select.Add("Description");
     options.Select.Add("Tags");
     options.Select.Add("Rooms");
     options.Select.Add("Rating");
     options.Select.Add("LastRenovationDate");
    
  7. 为查询和数据导入更新客户端引用。Update client references for queries and data import. 应将 SearchIndexClient 的实例更改为 SearchClientInstances of SearchIndexClient should be changed to SearchClient. 为了避免名称混乱,请确保在继续下一步之前捕获所有实例。To avoid name confusion, make sure you catch all instances before proceeding to the next step.

  8. 为索引、索引器、同义词映射和分析器对象更新客户端引用。Update client references for index, indexer, synonym map, and analyzer objects. 应将 SearchServiceClient 的实例更改为 SearchIndexClientInstances of SearchServiceClient should be changed to SearchIndexClient.

  9. 尽可能多地更新类、方法和属性以使用新库的 API。As much as possible, update classes, methods, and properties to use the APIs of the new library. 可以从命名差异部分来开始了解,但也可以查看更改日志The naming differences section is a place to start but you can also review the change log.

    如果在查找等效 API 时遇到困难,建议你在 https://github.com/MicrosoftDocs/azure-docs/issues 上记录问题,以便我们可以改进文档或调查问题。If you have trouble finding equivalent APIs, we suggest logging an issue on https://github.com/MicrosoftDocs/azure-docs/issues so that we can improve the documentation or investigate the problem.

  10. 重新生成解决方案。Rebuild the solution. 在修复了任何生成错误或警告后,可以对应用程序进行其他更改,以利用新功能After fixing any build errors or warnings, you can make additional changes to your application to take advantage of new functionality.

版本 11 中的中断性变更Breaking changes in version 11

考虑到对库和 API 的全面更改,升级到版本 11 是一项重大升级,你的代码将不再后向兼容版本 10 及更低版本。从这个意义上说,这是一项中断性变更。Given the sweeping changes to libraries and APIs, an upgrade to version 11 is non-trivial and constitutes a breaking change in the sense that your code will no longer be backward compatible with version 10 and earlier. 若要全面了解差异,请参阅 Azure.Search.Documents更改日志For a thorough review of the differences, see the change log for Azure.Search.Documents.

就服务版本更新而言,版本 11 中的代码更改与现有功能(而不仅仅是 API 重构)相关,你会发现以下行为更改:In terms of service version updates, where code changes in version 11 relate to existing functionality (and not just a refactoring of the APIs), you will find the following behavior changes:

  • BM25 排名算法将以前的排名算法替换为更新的技术。BM25 ranking algorithm replaces the previous ranking algorithm with newer technology. 新服务将自动使用此算法。New services will use this algorithm automatically. 对于现有服务,必须将参数设置为使用新算法。For existing services, you must set parameters to use the new algorithm.

  • 在此版本中,NULL 值的排序结果发生了变化,如果排序是 asc,则 NULL 值首先出现;如果排序是 desc,则 NULL 值最后出现。Ordered results for null values have changed in this version, with null values appearing first if the sort is asc and last if the sort is desc. 如果你编写了代码来处理如何对 NULL 值排序,则应查看该代码并可在不再需要时将其删除。If you wrote code to handle how null values are sorted, you should review and potentially remove that code if it's no longer necessary.

后续步骤Next steps