Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
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 login
command.
- 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 create
command to create a new resource group in your subscription.az group create \ --name "<resource-group-name>" \ --location "<location>"
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"
Create a new keyspace using
az cosmosdb cassandra keyspace create
namedcosmicworks
.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 create
command 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 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}"
Record the value of the
contactPoint
andusername
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.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"
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.
Start in an empty directory.
Create a new .NET console application
dotnet new console
Add the
CassandraCSharpDriver
package from NuGet.dotnet add package CassandraCSharpDriver
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.
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.Authentication
Cassandra
Cassandra.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
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);
Construct a new
Cluster
object 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
session
variable using theConnectAsync
method passing in the name of the target keyspace (cosmicworks
).using ISession session = await cluster.ConnectAsync("cosmicworks");
Create a new
mapper
variable by using theMapper
class constructor passing in the recently createdsession
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.
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.
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
InsertAsync
method passing in theproduct
variable 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
readQuery
with a CQL query that matches items with the sameid
field.string readQuery = "SELECT * FROM product WHERE id = ? LIMIT 1";
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";
Use the
SingleAsync<>
generic method to run the query stored inreadQuery
, pass in theid
variable as an argument, and map the output to theProduct
type. 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
findQuery
andcategory
with 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
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>"