Azure 搜索 SDK:如何指定数据源

Azure Search SDK: how to specify data source

我们厌倦了在开发过程中手动创建 Azure 搜索索引,所以我正在编写一个控制台应用程序来为我们做这件事。我们在 Azure 中已经有一个数据源,它是一个数据库视图。该视图将提供索引。我的问题是如何在创建索引时指定该数据源?到目前为止,这是我的代码(不包括 Employee class 定义):

using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;

namespace AdvancedSearchIndexGenerator
{
    class Program
    {
        static void Main()
        {
            SearchServiceClient client = new SearchServiceClient(Util.AzureSearchServiceName, new SearchCredentials(Util.AzureSearchApiKey));

            var definition = new Index()
            {
                Name = Util.AzureSearchIndexName,
                Fields = FieldBuilder.BuildForType<Employee>()
            };

            client.Indexes.Create(definition);
        }
    }
}

创建 Azure 搜索数据源是创建索引后的单独步骤

You can create Azure Search Data Source in 2 ways:

  1. Using Azure Search Service REST API
  2. Using Microsoft.Azure.Search NuGet package in C# Code

使用的 NuGet 包(很旧,这些包的较新版本可能有不同的实现):

  • 包 id="Microsoft.Azure.Search" 版本="1.1.1" targetFramework="net461"
  • 包 id="Microsoft.Rest.ClientRuntime.Azure" 版本="2.5.2" targetFramework="net45"

下面编写了示例 C# 代码以使用 CosmosDB 创建 Azure 搜索数据源:

using Microsoft.Azure.Search.Models;
using Microsoft.Rest.Azure;

DataSource dataSource = CreateDataSource(sqlQuery, collectionName, indexName, dataSourceName, dataSourceConnectionString);
AzureOperationResponse<DataSource> operation = await client.DataSources.CreateOrUpdateWithHttpMessagesAsync(dataSource);

private DataSource GetDataSource(string sqlQuery, string collectionName, string indexName, string dataSourceName, string dataSourceConnectionString)
{
    DataSource dataSource = new DataSource();
    dataSource.Name = dataSourceName;
    dataSource.Container = GetDataSourceContainer(sqlQuery, collectionName);
    dataSource.Credentials = new DataSourceCredentials(dataSourceConnectionString);
    dataSource.Type = "documentdb";
    return dataSource;
}       

private DataContainer GetDataSourceContainer(string sqlQuery, string collectionName)
{
    DataContainer container = new DataContainer();
    container.Query = sqlQuery;
    container.Name = collectionName;
    return container;
}

您在创建索引时没有指定数据源。您可以在创建索引器时指定数据源,该索引器将从数据源中提取数据并将其推送到索引中。

您会注意到您可以将 dataSourceName 作为参数传递给 Indexer creation

谢谢,

路易斯·卡布雷拉 | Azure 搜索