Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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.
The latest version of the Azure CLI in Azure Cloud Shell.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
az logincommand.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
- .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.
If you don't already have a target resource group, use the
az group createcommand to create a new resource group in your subscription.az group create \ --name "<resource-group-name>" \ --___location "<___location>"Use the
az cosmosdb createcommand 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"Create a new keyspace using
az cosmosdb cassandra keyspace createnamedcosmicworks.az cosmosdb cassandra keyspace create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"Create a new JSON object to represent your schema using a multi-line Bash command. Then, use the
az cosmosdb cassandra table createcommand to create a new table namedproducts.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.
Use
az cosmosdb showto 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}"Record the value of the
contactPointandusernameproperties 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.Use
az cosmosdb keys listto get the keys for the account.az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"Record the value of the
primaryMasterKeyproperty 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.
Start in an empty directory.
Create a new .NET console application
dotnet new consoleAdd the
CassandraCSharpDriverpackage from NuGet.dotnet add package CassandraCSharpDriverBuild 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.
Open the Program.cs file in your integrated development environment (IDE).
Delete any existing content within the file.
Add using directives for the following namespaces:
System.Security.AuthenticationCassandraCassandra.Mapping
using System.Security.Authentication; using Cassandra; using Cassandra.Mapping;Create string constant variables for the credentials collected earlier in this guide. Name the variables
username,password, andcontactPoint.const string username = "<username>"; const string password = "<password>"; const string contactPoint = "<contact-point>";Create a new
SSLoptionsobject 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);Construct a new
Clusterobject using the fluentCluster.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();Create a new
sessionvariable using theConnectAsyncmethod passing in the name of the target keyspace (cosmicworks).using ISession session = await cluster.ConnectAsync("cosmicworks");Create a new
mappervariable by using theMapperclass constructor passing in the recently createdsessionvariable.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.
Define a new record type named
Productwith fields corresponding to the table created earlier in this guide.Type IdstringNamestringCategorystringQuantityintPricedecimalClearanceboolrecord 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.
Create a new object of type
Product. Store the object in a variable namedproduct.Product product = new() { Id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", Name = "Yamba Surfboard", Category = "gear-surf-surfboards", Quantity = 12, Price = 850.00m, Clearance = false };Asynchronously invoke the
InsertAsyncmethod passing in theproductvariable created in the previous step.await mapper.InsertAsync(product);
Read data
Then, read data that was previously upserted into the table.
Create a new string variable named
readQuerywith a CQL query that matches items with the sameidfield.string readQuery = "SELECT * FROM product WHERE id = ? LIMIT 1";Create a string variable named
idwith the same value as the product created earlier in this guide.string id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb";Use the
SingleAsync<>generic method to run the query stored inreadQuery, pass in theidvariable as an argument, and map the output to theProducttype. Store the result of this operation in a variable of typeProduct.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.
Create string variables named
findQueryandcategorywith the CQL query and required parameter.string findQuery = "SELECT * FROM product WHERE category = ? ALLOW FILTERING"; string category = "gear-surf-surfboards";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 typeIEnumerable<Product>namedqueriedProducts.IEnumerable<Product> queriedProducts = await mapper.FetchAsync<Product>(findQuery, [category]);Use a
foreachloop 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>"