DynamoDB Primary Keys: Partition Key and Sort Key

beginner
12 min

DynamoDB Primary Keys: Partition Key and Sort Key

Welcome to our deep dive into understanding DynamoDB Primary Keys - Partition Key and Sort Key! 🎯

DynamoDB is a fast and flexible NoSQL database service provided by AWS. In this tutorial, we'll explore the two primary keys that every DynamoDB table must have - Partition Key and Sort Key. Let's start with the basics!

Understanding Partition Key (Primary Key)

The Partition Key is the primary key in DynamoDB. It's used to distribute data across multiple partitions (tables) within a table, making it easy to retrieve data efficiently. Think of it as a unique identifier for each item in a table.

📝 Note: A table can have only one Partition Key.

Here's a simple example:

json
{ "TableName": "Users", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" // Partition Key } ], "AttributeDefinitions": [ { "AttributeName": "UserId", "AttributeType": "N" // Number } ] }

In the above example, we've defined a table named "Users" with a Partition Key "UserId". This means that each item in the Users table will have a unique UserId.

Understanding Sort Key (Secondary Index)

The Sort Key, also known as the Secondary Index, is used to sort items within a partition based on a specific attribute. This helps in organizing and querying large amounts of data more efficiently.

💡 Pro Tip: A table can have multiple Sort Keys, but each Sort Key should have a unique name.

Here's an example of a table with a Sort Key:

json
{ "TableName": "Users", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" // Partition Key }, { "AttributeName": "UserName", "KeyType": "RANGE" // Sort Key } ], "AttributeDefinitions": [ { "AttributeName": "UserId", "AttributeType": "N" // Number }, { "AttributeName": "UserName", "AttributeType": "S" // String } ] }

In this example, we've added a Sort Key "UserName" to our Users table. Now, items in the Users table will be sorted by UserName within each UserId partition.

Partition Key vs Sort Key

The main difference between Partition Key and Sort Key lies in their purpose and how they're used:

  • Partition Key is used to distribute data across multiple partitions.
  • Sort Key is used to sort items within a partition and for efficient querying.

Quiz Time!

Quick Quiz
Question 1 of 1

What are the two primary keys in DynamoDB?

That's it for today! In the next lesson, we'll dive deeper into understanding different Key Types (Hash Key, Range Key, and Composite Key) and Attribute Types in DynamoDB. Stay tuned! 💡📝

Remember, practice is key! Keep exploring, coding, and learning! ✅