Configure an Azure Cosmos DB for NoSQL container’s index policy using the SDK

Indexing policies can be managed from any of the Azure Cosmos DB SDKs. The .NET SDK specifically includes a set of classes that can be used to architect and push a new indexing policy to a container in Azure Cosmos DB for NoSQL.

In this lab, you’ll create a custom indexing policy for a container using the .NET SDK

Prepare your development environment

If you have not already cloned the lab code repository for DP-420 to the environment where you’re working on this lab, follow these steps to do so. Otherwise, open the previously cloned folder in Visual Studio Code.

  1. Start Visual Studio Code.

    📝 If you are not already familiar with the Visual Studio Code interface, review the Get Started guide for Visual Studio Code

  2. Open the command palette and run Git: Clone to clone the https://github.com/microsoftlearning/dp-420-cosmos-db-dev GitHub repository in a local folder of your choice.

    💡 You can use the CTRL+SHIFT+P keyboard shortcut to open the command palette.

  3. Once the repository has been cloned, open the local folder you selected in Visual Studio Code.

Create an Azure Cosmos DB for NoSQL account

Azure Cosmos DB is a cloud-based NoSQL database service that supports multiple APIs. When provisioning an Azure Cosmos DB account for the first time, you will select which of the APIs you want the account to support (for example, Mongo API or NoSQL API). Once the Azure Cosmos DB for NoSQL account is done provisioning, you can retrieve the endpoint and key and use them to connect to the Azure Cosmos DB for NoSQL account using the Azure SDK for .NET or any other SDK of your choice.

  1. In a new web browser window or tab, navigate to the Azure portal (portal.azure.com).

  2. Sign into the portal using the Microsoft credentials associated with your subscription.

  3. Select + Create a resource, search for Cosmos DB, and then create a new Azure Cosmos DB for NoSQL account resource with the following settings, leaving all remaining settings to their default values:

    Setting Value
    Subscription Your existing Azure subscription
    Resource group Select an existing or create a new resource group
    Account Name Enter a globally unique name
    Location Choose any available region
    Capacity mode Provisioned throughput
    Apply Free Tier Discount Do Not Apply

    📝 Your lab environments may have restrictions preventing you from creating a new resource group. If that is the case, use the existing pre-created resource group.

  4. Wait for the deployment task to complete before continuing with this task.

  5. Go to the newly created Azure Cosmos DB account resource and navigate to the Keys pane.

  6. This pane contains the connection details and credentials necessary to connect to the account from the SDK. Specifically:

    1. Notice the URI field. You will use this endpoint value later in this exercise.

    2. Notice the PRIMARY KEY field. You will use this key value later in this exercise.

  7. Return to Visual Studio Code.

Create a new indexing policy using the .NET SDK

The .NET SDK contains a suite of classes related to the parent Microsoft.Azure.Cosmos.IndexingPolicy class to build new indexing policies in code.

  1. In the Explorer pane, browse to the 12-custom-index-policy folder.

  2. Open the script.cs code file.

  3. Update the existing variable named endpoint with its value set to the endpoint of the Azure Cosmos DB account you created earlier.

     string endpoint = "<cosmos-endpoint>";
    

    📝 For example, if your endpoint is: https­://dp420.documents.azure.com:443/, then the C# statement would be: string endpoint = “https­://dp420.documents.azure.com:443/”;.

  4. Update the existing variable named key with its value set to the key of the Azure Cosmos DB account you created earlier.

     string key = "<cosmos-key>";
    

    📝 For example, if your key is: fDR2ci9QgkdkvERTQ==, then the C# statement would be: string key = “fDR2ci9QgkdkvERTQ==”;.

  5. Create a new variable of type IndexingPolicy named policy using the default empty constructor:

     IndexingPolicy policy = new ();
    
  6. Set the IndexingMode property of the policy variable to a value of IndexingMode.Consistent:

     policy.IndexingMode = IndexingMode.Consistent;
    
  7. Add a new object of type ExcludedPath with its Path property set to a value of /* to the ExcludedPaths collection property in the policy variable:

     policy.ExcludedPaths.Add(
         new ExcludedPath{ Path = "/*" }
     );
    
  8. Add a new object of type IncludedPath with its Path property set to a value of /name/? to the IncludedPaths collection property in the policy variable:

     policy.IncludedPaths.Add(
         new IncludedPath{ Path = "/name/?" }
     );
    
  9. Create a new variable of type ContainerProperties named options passing in the values products and /categoryId as constructor parameters:

     ContainerProperties options = new ("products", "/categoryId");
    
  10. Assign the policy variable to the IndexingPolicy property of the options variable:

     options.IndexingPolicy = policy;
    
  11. Asynchronously invoke the CreateContainerIfNotExistsAsync method of the database variable passing in the options variable as a constructor parameter and storing the result in a variable of type Container named container:

     Container container = await database.CreateContainerIfNotExistsAsync(options);
    
  12. Use the built-in Console.WriteLine static method to print the Id property of the Container class with a header titled Container Created:

     Console.WriteLine($"Container Created [{container.Id}]");
    
  13. Once you are done, your code file should now include:

     using System;
     using Microsoft.Azure.Cosmos;
    
     string endpoint = "<cosmos-endpoint>";
    
     string key = "<cosmos-key>";
    
     CosmosClient client = new CosmosClient(endpoint, key);
    
     Database database = await client.CreateDatabaseIfNotExistsAsync("cosmicworks");
        
     IndexingPolicy policy = new ();
     policy.IndexingMode = IndexingMode.Consistent;
     policy.ExcludedPaths.Add(
         new ExcludedPath{ Path = "/*" }
     );
     policy.IncludedPaths.Add(
         new IncludedPath{ Path = "/name/?" }
     );
    
     ContainerProperties options = new ("products", "/categoryId");
     options.IndexingPolicy = policy;
    
     Container container = await database.CreateContainerIfNotExistsAsync(options);
     Console.WriteLine($"Container Created [{container.Id}]");
    
  14. Save the script.cs file.

  15. In Visual Studio Code, open the context menu for the 12-custom-index-policy folder and then select Open in Integrated Terminal to open a new terminal instance.

  16. Build and run the project using the dotnet run command:

     dotnet run
    
  17. The script will now output the name of the newly created container:

     Container Created [products]
    
  18. Close the integrated terminal.

  19. Return to your web browser.

Observe an indexing policy created by the .NET SDK using the Data Explorer

Just like with any other indexing policy, you can use the Data Explorer to view policies that you pushed using the .NET SDKs. You will now use the portal to review the policy you created in this lab from code.

  1. Within the Azure Cosmos DB account resource, navigate to the Data Explorer pane.

  2. In the Data Explorer, expand the cosmicworks database node, then observe the new products container node within the NOSQL API navigation tree.

  3. Within the products container node of the NOSQL API navigation tree, select Scale & Settings.

  4. Observe the indexing policy within the Indexing Policy section:

     {
       "indexingMode": "consistent",
       "automatic": true,
       "includedPaths": [
         {
           "path": "/name/?"
         }
       ],
       "excludedPaths": [
         {
           "path": "/*"
         },
         {
           "path": "/\"_etag\"/?"
         }
       ]
     }
    

    📝 This is the JSON representation of the indexing policy you created using the .NET SDK in this lab.

  5. Close your web browser window or tab.