What Is Partition Key in Cosmos DB: Simple Explanation and Example
partition key is a property in your data that Cosmos DB uses to split and organize your data into smaller parts called partitions. This helps Cosmos DB store and access data efficiently and scale automatically as your data grows.How It Works
Imagine you have a huge library of books, and you want to organize them so you can find any book quickly. Instead of putting all books on one big shelf, you divide them into sections based on a category, like genre or author. In Cosmos DB, the partition key works like that category. It tells Cosmos DB how to split your data into smaller groups called partitions.
Each partition holds data items that share the same partition key value. This way, Cosmos DB can quickly find and manage data by looking only in the right partition, not the entire database. This makes reading and writing data faster and helps Cosmos DB handle lots of data and users without slowing down.
Example
This example shows how to create a Cosmos DB container with a partition key on the property /category. Each item will be grouped by its category value.
const { CosmosClient } = require("@azure/cosmos"); async function createContainer() { const endpoint = "https://your-cosmos-account.documents.azure.com:443/"; const key = "your-primary-key"; const client = new CosmosClient({ endpoint, key }); const database = client.database("SampleDB"); const containerDefinition = { id: "Products", partitionKey: { paths: ["/category"], kind: "Hash" } }; const { container } = await database.containers.createIfNotExists(containerDefinition); console.log("Container created with partition key /category"); } createContainer().catch(console.error);
When to Use
Use a partition key in Cosmos DB when you expect your data to grow large or when you want your database to handle many requests smoothly. The partition key helps Cosmos DB split data so it can work faster and scale automatically.
For example, if you have an online store, you might use category or customerId as a partition key. This groups products or orders by category or customer, making it easy to find and update related data quickly.
Key Points
- The partition key is a property in your data used to split data into partitions.
- It helps Cosmos DB scale and perform well with large data and many users.
- Choose a partition key with many distinct values to balance data evenly.
- Once set, the partition key cannot be changed without creating a new container.