Welcome back! Previously, we explored Amazon DynamoDB, a NoSQL database provided by AWS, noted for its flexibility in handling schema-less data management. This session deepens our dive into DynamoDB by focusing on the essential components of the database—tables.
In this lesson, we'll concentrate on how data is structured in DynamoDB tables, consisting of items grouped by attributes, such as a name or a date. We'll cover crucial concepts such as primary keys, data types, and capacity modes, equipping you with the knowledge to effectively create and manage tables using Python’s Boto3. Mastering these aspects is essential for building applications that are both scalable and efficient.
In DynamoDB, each item within a table is uniquely identified by a primary key, which is critical for efficient data retrieval and management. The primary key can consist of either a single attribute, known as a partition key, or a combination of two attributes: a partition key and a sort key.
-
Partition Key: Also known as a Hash Key, this key determines the distribution of data across various physical storage partitions in DynamoDB. Multiple items in the table may have identical values for the partition key. However, if a table uses only the partition key as its primary key, that key value must be unique for each item in the table as it's the sole identifier for the item's location in the table.
-
Sort Key : Also known as a range key, this key allows items with the same partition key to be stored and retrieved in a sorted order. The sort key provides the necessary uniqueness when combined with the partition key, ensuring that no two items in the same partition have the same sort key value.
In a correct setup with a composite primary key, consider a table named BlogPosts where AuthorID serves as the partition key and PostDate as the sort key. This setup allows each post by the same author to be uniquely identified by the date:
| AuthorID | PostDate | Title |
|---|---|---|
| A1 | 2020-01-01 | New Year Reflections |
| A1 | 2020-01-02 | Another Day in Life |
However, if the same author writes multiple posts on the same date, and the PostDate is not combined with another unique attribute, this can result in incorrect setup as shown below:
| AuthorID | PostDate | Title |
|---|---|---|
| A1 | 2020-01-01 | Morning Thoughts |
| A1 | 2020-01-01 | Evening Reflections |
In this scenario, both posts from the same day are not uniquely distinguishable solely by the primary key, which could lead to one post overwriting the other if not managed properly. This example emphasizes the importance of ensuring that the primary key, whether simple or composite, effectively distinguishes each item in the table. Understanding these keys and their impact on data distribution and access is fundamental for designing efficient DynamoDB tables.
