Step 2 - Create and load Search Index with .NET

Continue to build your search-enabled website by following these steps:

  • Create a search resource
  • Create a new index
  • Import data with .NET using the sample script and Azure SDK Azure.Search.Documents.

Create an Azure AI Search resource

Create a new search resource from the command line using either the Azure CLI or Azure PowerShell. You also retrieve a query key used for read-access to the index, and get the built-in admin key used for adding objects.

You must have Azure CLI or Azure PowerShell installed on your device. If you aren't a local admin on your device, choose Azure PowerShell and use the Scope parameter to run as the current user.

Note

This task doesn't require the Visual Studio Code extensions for Azure CLI and Azure PowerShell. Visual Studio Code recognizes the command line tools without the extensions.

  1. In Visual Studio Code, under Terminal, select New Terminal.

  2. Connect to Azure:

    az login
    
  3. Before creating a new search service, list the existing services for your subscription:

    az resource list --resource-type Microsoft.Search/searchServices --output table
    

    If you have a service that you want to use, note the name, and then skip ahead to the next section.

  4. Create a new search service. Use the following command as a template, substituting valid values for the resource group, service name, tier, region, partitions, and replicas. The following statement uses the "cognitive-search-demo-rg" resource group created in a previous step and specifies the "free" tier. If your Azure subscription already has a free search service, specify a billable tier such as "basic" instead.

    az search service create --name my-cog-search-demo-svc --resource-group cognitive-search-demo-rg --sku free --partition-count 1 --replica-count 1
    
  5. Get a query key that grants read access to a search service. A search service is provisioned with two admin keys and one query key. Substitute valid names for the resource group and search service. Copy the query key to Notepad so that you can paste it into the client code in a later step:

    az search query-key list --resource-group cognitive-search-demo-rg --service-name my-cog-search-demo-svc
    
  6. Get a search service admin API key. An admin API key provides write access to the search service. Copy either one of the admin keys to Notepad so that you can use it in the bulk import step that creates and loads an index:

    az search admin-key show --resource-group cognitive-search-demo-rg --service-name my-cog-search-demo-svc
    

The script uses the Azure SDK for Azure AI Search:

  1. In Visual Studio Code, open the Program.cs file in the subdirectory, search-website-functions-v4/bulk-insert, replace the following variables with your own values to authenticate with the Azure Search SDK:

    • YOUR-SEARCH-RESOURCE-NAME
    • YOUR-SEARCH-ADMIN-KEY
    
    using Azure;
    using Azure.Search.Documents;
    using Azure.Search.Documents.Indexes;
    using Azure.Search.Documents.Indexes.Models;
    using AzureSearch.BulkInsert;
    using ServiceStack;
    
    const string BOOKS_URL = "https://raw.githubusercontent.com/Azure-Samples/azure-search-sample-data/main/good-books/books.csv";
    const string SEARCH_ENDPOINT = "https://YOUR-SEARCH-RESOURCE-NAME.search.windows.net";
    const string SEARCH_KEY = "YOUR-SEARCH-ADMIN-KEY";
    const string SEARCH_INDEX_NAME = "good-books";
    
    Uri searchEndpointUri = new(SEARCH_ENDPOINT);
    
    SearchClient client = new(
        searchEndpointUri,
        SEARCH_INDEX_NAME,
        new AzureKeyCredential(SEARCH_KEY));
    
    SearchIndexClient clientIndex = new(
        searchEndpointUri,
        new AzureKeyCredential(SEARCH_KEY));
    
    await CreateIndexAsync(clientIndex);
    await BulkInsertAsync(client);
    
    static async Task CreateIndexAsync(SearchIndexClient clientIndex)
    {
        Console.WriteLine("Creating (or updating) search index");
        SearchIndex index = new BookSearchIndex(SEARCH_INDEX_NAME);
        var result = await clientIndex.CreateOrUpdateIndexAsync(index);
    
        Console.WriteLine(result);
    }
    
    static async Task BulkInsertAsync(SearchClient client)
    {
        Console.WriteLine("Download data file");
        using HttpClient httpClient = new();
    
        var csv = await httpClient.GetStringAsync(BOOKS_URL);
    
        Console.WriteLine("Reading and parsing raw CSV data");
        var books =
            csv.ReplaceFirst("book_id", "id").FromCsv<List<BookModel>>();
    
        Console.WriteLine("Uploading bulk book data");
        _ = await client.UploadDocumentsAsync(books);
    
        Console.WriteLine("Finished bulk inserting book data");
    }
    
  2. Open an integrated terminal in Visual Studio Code for the project directory's subdirectory, search-website-functions-v4/bulk-insert, then run the following command to install the dependencies.

    dotnet restore
    
  1. Continue using the integrated terminal in Visual Studio for the project directory's subdirectory, search-website-functions-v4/bulk-insert, to run the following bash command to run the Program.cs script:

    dotnet run
    
  2. As the code runs, the console displays progress.

  3. When the upload is complete, the last statement printed to the console is "Finished bulk inserting book data".

Review the new Search Index

Once the upload completes, the search index is ready to use. Review your new index in Azure portal.

  1. In Azure portal, find the search service you created in the previous step.

  2. On the left, select Indexes, and then select the good-books index.

    Expandable screenshot of Azure portal showing the index.

  3. By default, the index opens in the Search explorer tab. Select Search to return documents from the index.

    Expandable screenshot of Azure portal showing search results

Rollback bulk import file changes

Use the following git command in the Visual Studio Code integrated terminal at the bulk-insert directory, to roll back the changes. They aren't needed to continue the tutorial and you shouldn't save or push these secrets to your repo.

git checkout .

Copy your Search resource name

Note your Search resource name. You'll need this to connect the Azure Function app to your search resource.

Caution

While you may be tempted to use your search admin key in the Azure Function, that isn't following the principle of least privilege. The Azure Function will use the query key to conform to least privilege.

Next steps

Deploy your Static Web App