Concepts
When it comes to designing and implementing native applications using Microsoft Azure Cosmos DB, it is essential to understand the concept of primary and unique keys. These keys play a crucial role in ensuring data integrity and efficient query execution within the Cosmos DB environment. In this article, we will explore how to identify primary and unique keys, their significance, and how to work with them in your application.
1. Primary Keys:
A primary key uniquely identifies a document within a specific container in Azure Cosmos DB. It can be either automatically generated by the system or defined explicitly by the developer. The primary key value must be unique for each document within the container. The primary key can be used to facilitate fast and efficient retrieval of documents using point reads.
To identify the primary key for a container, you can refer to the container’s definition in your application code or the Azure portal. In the Azure portal, navigate to the database account, select the desired database and container, and then click on the “Keys” tab. The value displayed under the “Primary Key” section is the primary key for the container.
Here is an example of how to work with primary keys in C# code:
using Microsoft.Azure.Cosmos;
// Create the Cosmos client instance
string connectionString = "your_connection_string";
CosmosClient cosmosClient = new CosmosClient(connectionString);
// Define the database and container
string databaseId = "your_database_id";
string containerId = "your_container_id";
// Get the container reference
Container container = cosmosClient.GetContainer(databaseId, containerId);
// Create a new document to insert
dynamic newDocument = new
{
id = "your_document_id",
name = "John Doe",
age = 30
};
// Set the primary key for the document
newDocument.id = Guid.NewGuid().ToString(); // Generate a unique identifier
// Insert the document into the container
ItemResponse
In the above code snippet, we first create an instance of the Cosmos client using the connection string. Then we define the database and container we want to work with. After that, we retrieve the container reference using the client and insert a new document into the container with a unique primary key.
2. Unique Keys:
Unique keys in Azure Cosmos DB provide a way to enforce uniqueness on specific properties within a container. Unlike the primary key, which is unique for each document, unique keys ensure uniqueness for one or more properties across all documents within a container. By defining unique keys, you can prevent duplicate values and maintain data integrity.
To identify unique keys for a container, you can refer to the container’s definition in your application code or the Azure portal. In the Azure portal, navigate to the database account, select the desired database and container, and then click on the “Keys” tab. The values displayed under the “Unique Key” section are the unique keys defined for the container.
Here is an example of how to define and work with unique keys in C# code:
using Microsoft.Azure.Cosmos;
// Create the Cosmos client instance
string connectionString = "your_connection_string";
CosmosClient cosmosClient = new CosmosClient(connectionString);
// Define the database and container
string databaseId = "your_database_id";
string containerId = "your_container_id";
// Get the container reference
Container container = cosmosClient.GetContainer(databaseId, containerId);
// Define the unique key policy
UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy
{
UniqueKeys = new Collection
{
new UniqueKey { Paths = new Collection
new UniqueKey { Paths = new Collection
}
};
// Update the container definition with the unique key policy
await container.ReplaceContainerAsync(containerId, null, uniqueKeyPolicy);
In the above code snippet, we first create an instance of the Cosmos client using the connection string. Then we define the database and container we want to work with. After that, we retrieve the container reference using the client.
Next, we define a unique key policy and specify the properties for which uniqueness needs to be enforced. In this example, we have defined two unique keys, one for “property1” and another for “property2”. Finally, we update the container definition with the unique key policy using the ReplaceContainerAsync
method.
By understanding and utilizing primary and unique keys effectively, you can ensure data integrity and enable efficient querying in your native applications built on Microsoft Azure Cosmos DB. Take advantage of these features to enhance your application’s performance and reliability while working with distributed and scalable databases.
Answer the Questions in Comment Section
Which of the following statements about primary keys in Microsoft Azure Cosmos DB is true?
- a) Primary keys are automatically assigned by the database system.
- b) Primary keys must be unique within a single partition.
- c) Primary keys can be edited or modified after they are assigned.
- d) Primary keys are not required for data storage in Cosmos DB.
Correct answer: b) Primary keys must be unique within a single partition.
In Microsoft Azure Cosmos DB, what is a unique key policy used for?
- a) To ensure that all documents have a primary key.
- b) To enforce uniqueness of a specific property within a collection.
- c) To limit the number of read requests per second for a collection.
- d) To automatically create indexes for frequently accessed properties.
Correct answer: b) To enforce uniqueness of a specific property within a collection.
Which of the following statements about the partition key in Azure Cosmos DB is correct?
- a) The partition key determines the number of physical partitions in a database.
- b) Changing the partition key requires migrating data to a new container.
- c) Partition key values must be unique across all containers in a database.
- d) The partition key can be any property or combination of properties.
Correct answer: d) The partition key can be any property or combination of properties.
What is the purpose of a composite primary key in Azure Cosmos DB?
- a) To define multiple properties as the primary key for a document.
- b) To create a relationship between different documents within a collection.
- c) To enable cross-document transactions within a partition.
- d) Composite primary keys are not supported in Azure Cosmos DB.
Correct answer: a) To define multiple properties as the primary key for a document.
True or False: In Azure Cosmos DB, the unique key constraint is implemented at the collection level.
Correct answer: False.
What is the maximum number of unique keys that can be defined for a single collection in Azure Cosmos DB?
- a) 10
- b) 100
- c) 1000
- d) There is no maximum limit.
Correct answer: d) There is no maximum limit.
Which of the following statements is true regarding unique key constraints in Azure Cosmos DB?
- a) Unique key constraints are automatically generated based on the document schema.
- b) Unique key constraints can be enforced only for single-partition collections.
- c) Unique key constraints can be applied to both partitioned and non-partitioned collections.
- d) Unique key constraints are not supported in Azure Cosmos DB.
Correct answer: c) Unique key constraints can be applied to both partitioned and non-partitioned collections.
True or False: In Azure Cosmos DB, primary keys and unique keys can be used interchangeably.
Correct answer: False.
What happens when a document with a duplicate primary key is inserted into Azure Cosmos DB?
- a) The document is rejected and an error is returned.
- b) The document is updated with the new values.
- c) The document is overwritten by the new document.
- d) The document is inserted as a new version.
Correct answer: a) The document is rejected and an error is returned.
What is the maximum size of a primary key in Azure Cosmos DB?
- a) 256 bytes
- b) 1 KB
- c) 2 KB
- d) There is no maximum size limit.
Correct answer: d) There is no maximum size limit.
Great explanation on primary and unique keys. It really helped me understand the fundamentals for DP-420.
I’m still a bit confused about the difference between the two. Can anyone elaborate?
Needed this for my prep! Thanks!
How does Cosmos DB handle unique keys with partitioning?
Clarified my doubts perfectly.
I actually found this blog lacking depth on unique key constraints in multi-region setups.
How does one define a composite primary key in Cosmos DB?
This is exactly what I was looking for!