Welcome back! In our previous discussions, we've explored the essentials of setting up DynamoDB tables and the key concepts behind AWS's NoSQL database service. Today, we dive into the practical aspects of DynamoDB by learning how to add data to our tables. We'll focus on using the PutItem and BatchWriteItem operations to insert single and multiple items, respectively.
Our practical examples will utilize a Students table, structured with the following attributes: student_id (serving as the primary key), name, age, and major. Here's a quick glance at the existing data setup:
| student_id (PK) | name | age | major |
|---|---|---|---|
| 1 | Alice | 20 | Computer Science |
| 2 | Bob | 22 | Mathematics |
This session aims to expand this table by adding more student records, allowing us to apply our learning in a hands-on manner. Let's get started by adding new entries and examining how DynamoDB handles these data manipulation tasks.
Let's start by adding a new student, John, who is studying Physics, to our Students table. To do this, we'll use the PutItem operation, which is designed for creating a single item within your DynamoDB table. Here's how you can add John's details:
In this example, the put_item method on the table object is used to insert a new record. The Item parameter is a dictionary that specifies the attributes of the student—each key in the dictionary corresponds to an attribute in our DynamoDB table.
This operation is straightforward and effective for adding individual records, making it ideal for situations where you need to insert data sporadically or one item at a time. However, it's important to be aware of a few considerations:
- Item Size Limits: Each item, including all its attributes, cannot exceed 400 KB.
- Consistency: By default,
PutItemoperations ensure eventual consistency. You can opt for strongly consistent reads if your application requires it, albeit at double the read cost. - Throughput Consumption: Each
PutItemrequest consumes write capacity units based on the item size. In provisioned capacity mode, managing this carefully is necessary to avoid throttling.
