What is Primary Key in DynamoDB: Definition and Usage
primary key uniquely identifies each item in a table. It can be a single attribute called a partition key or a combination of partition key and sort key to organize and access data efficiently.How It Works
Think of a DynamoDB table like a big filing cabinet. The primary key is like the unique label on each folder that helps you find exactly one folder without confusion. This key ensures that no two items in the table have the same identifier.
The primary key can be simple, using just one attribute called the partition key. This key decides which drawer (partition) the folder goes into. If you want to organize folders further inside the drawer, you use a sort key along with the partition key. This combination lets you store multiple related items under the same partition key but sorted by the sort key, like having folders sorted by date inside the same drawer.
Example
This example shows how to create a DynamoDB table with a composite primary key using AWS SDK for JavaScript. The partition key is UserId and the sort key is OrderId.
import { DynamoDBClient, CreateTableCommand } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({ region: "us-east-1" }); const params = { TableName: "Orders", KeySchema: [ { AttributeName: "UserId", KeyType: "HASH" }, // Partition key { AttributeName: "OrderId", KeyType: "RANGE" } // Sort key ], AttributeDefinitions: [ { AttributeName: "UserId", AttributeType: "S" }, { AttributeName: "OrderId", AttributeType: "S" } ], BillingMode: "PAY_PER_REQUEST" }; async function createTable() { try { const data = await client.send(new CreateTableCommand(params)); console.log("Table created successfully", data.TableDescription.TableName); } catch (err) { console.error("Error creating table", err); } } createTable();
When to Use
Use a primary key in DynamoDB whenever you need to uniquely identify each item in your table. This is essential for fast lookups, updates, and deletes without scanning the entire table.
If your data naturally groups by one attribute, like a user ID, use a simple partition key. If you want to store multiple related records for the same user, like orders or messages, use a composite key with a partition key and sort key.
For example, an e-commerce app can use UserId as the partition key and OrderId as the sort key to quickly find all orders for a user sorted by order date.
Key Points
- The primary key uniquely identifies each item in a DynamoDB table.
- It can be a single
partition keyor a composite key withpartition keyandsort key. - The partition key determines the partition where data is stored.
- The sort key allows sorting and grouping of related items within the same partition.
- Choosing the right primary key is crucial for efficient data access and performance.