2
votes

We're getting tired of creating our Azure Search index manually during development, so I'm writing a console app to do it for us. We already have a data source in Azure which is a database view. That view will feed the index. My question is how do I specify that data source when I create the index? Here's my code so far (not including the Employee class definition):

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);
        }
    }
}
2

2 Answers

1
votes

Creating Azure Search Data Source is the separate step after creating Index

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 Packages used (quite old, newer version of these packages may have different implementation):

  • package id="Microsoft.Azure.Search" version="1.1.1" targetFramework="net461"
  • package id="Microsoft.Rest.ClientRuntime.Azure" version="2.5.2" targetFramework="net45"

Sample C# code is written below to create an Azure Search Data Source with CosmosDB:

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;
}
0
votes

You don't specify the data source when you create the index. You can specify the data source when you create an indexer that will extract data from the data source and push it into the index.

You will notice that you can pass the dataSourceName as an argument to the Indexer creation.

Thanks,

Luis Cabrera | Azure Search