Modifica

Condividi tramite


Quickstart: Azure Cosmos DB for Apache Cassandra client library for .NET

Get started with the Azure Cosmos DB for Apache Cassandra client library for .NET to store, manage, and query unstructured data. Follow the steps in this guide to create a new account, install a .NET client library, connect to the account, perform common operations, and query your final sample data.

API reference documentation | Library source code | Package (NuGet)

Prerequisites

  • An Azure subscription

    • If you don't have an Azure subscription, create a free account before you begin.
  • .NET SDK 9.0 or later

Setting up

First, set up the account and development environment for this guide. This section walks you through the process of creating an account, getting its credentials, and then preparing your development environment.

Create an account

Start by creating an API for Apache Cassandra account. Once the account is created, create the keyspace and table resources.

  1. If you don't already have a target resource group, use the az group create command to create a new resource group in your subscription.

    az group create \
        --name "<resource-group-name>" \
        --location "<location>"
    
  2. Use the az cosmosdb create command to create a new Azure Cosmos DB for Apache Cassandra account with default settings.

    az cosmosdb create \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --locations "regionName=<location>" \
        --capabilities "EnableCassandra"
    
  3. Create a new keyspace using az cosmosdb cassandra keyspace create named cosmicworks.

    az cosmosdb cassandra keyspace create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. Create a new JSON object to represent your schema using a multi-line Bash command. Then, use the az cosmosdb cassandra table create command to create a new table named products.

    schemaJson=$(cat <<EOF
    {
      "columns": [
        {
          "name": "id",
          "type": "text"
        },
        {
          "name": "name",
          "type": "text"
        },
        {
          "name": "category",
          "type": "text"
        },
        {
          "name": "quantity",
          "type": "int"
        },
        {
          "name": "price",
          "type": "decimal"
        },
        {
          "name": "clearance",
          "type": "boolean"
        }
      ],
      "partitionKeys": [
        {
          "name": "id"
        }
      ]
    }
    EOF
    )
    
    az cosmosdb cassandra table create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --keyspace-name "cosmicworks" \
        --name "product" \
        --schema "$schemaJson"
    

Get credentials

Now, get the password for the client library to use to create a connection to the recently created account.

  1. Use az cosmosdb show to get the contact point and username for the account.

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. Record the value of the contactPoint and username properties from the previous commands' output. These properties' values are the contact point and username you use later in this guide to connect to the account with the library.

  3. Use az cosmosdb keys list to get the keys for the account.

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. Record the value of the primaryMasterKey property from the previous commands' output. This property's value is the password you use later in this guide to connect to the account with the library.

Prepare development environment

Then, configure your development environment with a new project and the client library. This step is the last required prerequisite before moving on to the rest of this guide.

  1. Start in an empty directory.

  2. Create a new .NET console application

    dotnet new console
    
  3. Add the CassandraCSharpDriver package from NuGet.

    dotnet add package CassandraCSharpDriver
    
  4. Build the project.

    dotnet build
    

Object model

Description
Cluster Represents the connection state to a cluster
ISession Thread-safe entities that hold a specific connection to a cluster
Mapper Cassandra Query Language (CQL) client used to run queries

Code examples

Authenticate client

Start by authenticating the client using the credentials gathered earlier in this guide.

  1. Open the Program.cs file in your integrated development environment (IDE).

  2. Delete any existing content within the file.

  3. Add using directives for the following namespaces:

    • System.Security.Authentication
    • Cassandra
    • Cassandra.Mapping
    using System.Security.Authentication;
    using Cassandra;
    using Cassandra.Mapping;
    
  4. Create string constant variables for the credentials collected earlier in this guide. Name the variables username, password, and contactPoint.

    const string username = "<username>";
    const string password = "<password>";
    const string contactPoint = "<contact-point>";
    
  5. Create a new SSLoptions object to ensure that you're using the transport layer security (TLS) 1.2 protocol, checking for certificate revocation, and not performing any extra client-side certification validation.

    SSLOptions sslOptions = new(
        sslProtocol: SslProtocols.Tls12,
        checkCertificateRevocation: true,
        remoteCertValidationCallback: (_, _, _, _) => true);
    
  6. Construct a new Cluster object using the fluent Cluster.Builder() syntax. Use the credential and configuration variables created in the previous steps.

    Cluster cluster = Cluster.Builder()
        .WithCredentials(username, password)
        .WithPort(10350)
        .AddContactPoint(contactPoint)
        .WithSSL(sslOptions)
        .Build();
    
  7. Create a new session variable using the ConnectAsync method passing in the name of the target keyspace (cosmicworks).

    using ISession session = await cluster.ConnectAsync("cosmicworks");
    
  8. Create a new mapper variable by using the Mapper class constructor passing in the recently created session variable.

    Mapper mapper = new(session);
    

Warning

Complete transport layer security (TLS) validation is disabled in this guide to simplify authentication. For production deployments, fully enable validation.

Upsert data

Next, upsert new data into a table. Upserting ensures that the data is created or replaced appropriately depending on whether the same data already exists in the table.

  1. Define a new record type named Product with fields corresponding to the table created earlier in this guide.

    Type
    Id string
    Name string
    Category string
    Quantity int
    Price decimal
    Clearance bool
    record Product
    {
        public required string Id { get; init; }
    
        public required string Name { get; init; }
    
        public required string Category { get; init; }
    
        public required int Quantity { get; init; }
    
        public required decimal Price { get; init; }
    
        public required bool Clearance { get; init; }
    }
    

    Tip

    In .NET, you can create this type in another file or create it at the end of the existing file.

  2. Create a new object of type Product. Store the object in a variable named product.

    Product product = new()
    {
        Id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
        Name = "Yamba Surfboard",
        Category = "gear-surf-surfboards",
        Quantity = 12,
        Price = 850.00m,
        Clearance = false
    };
    
  3. Asynchronously invoke the InsertAsync method passing in the product variable created in the previous step.

    await mapper.InsertAsync(product);
    

Read data

Then, read data that was previously upserted into the table.

  1. Create a new string variable named readQuery with a CQL query that matches items with the same id field.

    string readQuery = "SELECT * FROM product WHERE id = ? LIMIT 1";
    
  2. Create a string variable named id with the same value as the product created earlier in this guide.

    string id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb";
    
  3. Use the SingleAsync<> generic method to run the query stored in readQuery, pass in the id variable as an argument, and map the output to the Product type. Store the result of this operation in a variable of type Product.

    Product matchedProduct = await mapper.SingleAsync<Product>(readQuery, [id]);
    

Query data

Finally, use a query to find all data that matches a specific filter in the table.

  1. Create string variables named findQuery and category with the CQL query and required parameter.

    string findQuery = "SELECT * FROM product WHERE category = ? ALLOW FILTERING";
    string category = "gear-surf-surfboards";
    
  2. Use the two string variables and the FetchAsync<> generic method to asynchronously query multiple results. Store the result of this query in a variable of type IEnumerable<Product> named queriedProducts.

    IEnumerable<Product> queriedProducts = await mapper.FetchAsync<Product>(findQuery, [category]);
    
  3. Use a foreach loop to iterate over the query results.

    foreach (Product queriedProduct in queriedProducts)
    {
        // Do something here with each result
    }
    

Run the code

Run the newly created application using a terminal in your application directory.

dotnet run

Clean up resources

When you no longer need the account, remove the account from your Azure subscription by deleting the resource.

az cosmosdb delete \
    --resource-group "<resource-group-name>" \
    --name "<account-name>"

Next step