Aws. Lesson 2. Dynamodb
DynamoDB Tutorial with 4 Examples per Topic
1. Creating a Table
Example 1: Basic Table Creation
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.create_table(
TableName='Users',
KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}],
AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}],
ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)
print("Table created")
Explanation
Connects to DynamoDB using the boto3 library.
dynamodb = boto3.resource('dynamodb')
Creates a Users table with a primary key.
TableName='Users', KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}]
Defines UserID as a string attribute.
AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}]
Sets read/write capacity at 5 units each.
ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
Example 2: Creating a Table with Sort Key
table = dynamodb.create_table(
TableName='Orders',
KeySchema=[
{'AttributeName': 'OrderID', 'KeyType': 'HASH'},
{'AttributeName': 'CustomerID', 'KeyType': 'RANGE'}
],
AttributeDefinitions=[
{'AttributeName': 'OrderID', 'AttributeType': 'S'},
{'AttributeName': 'CustomerID', 'AttributeType': 'S'}
],
ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)
Explanation
Creates an Orders table with a primary and sort key.
KeySchema=[{'AttributeName': 'OrderID', 'KeyType': 'HASH'}, {'AttributeName': 'CustomerID', 'KeyType': 'RANGE'}]
Defines both keys as string attributes.
AttributeDefinitions=[{'AttributeName': 'OrderID', 'AttributeType': 'S'}, {'AttributeName': 'CustomerID', 'AttributeType': 'S'}]
Sort key allows querying by CustomerID.
KeyType='RANGE'
Uses ProvisionedThroughput to control costs.
ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
Example 3: List Tables
client = boto3.client('dynamodb')
response = client.list_tables()
print(response['TableNames'])
Explanation
Uses the DynamoDB client to interact with AWS.
client = boto3.client('dynamodb')
Retrieves a list of all tables.
response = client.list_tables()
Prints the table names in the account.
print(response['TableNames'])
Helps verify available tables before operations.
list_tables()
Example 4: Delete a Table
table = dynamodb.Table('Users')
table.delete()
print("Table deleted")
Explanation
Gets a reference to the Users table.
table = dynamodb.Table('Users')
Calls delete() to remove it.
table.delete()
Deletes the entire table permanently.
delete()
Prints a confirmation message.
print("Table deleted")
2. Inserting Data
Example 1: Insert a Single Item
table = dynamodb.Table('Users')
table.put_item(Item={
'UserID': '123',
'Name': 'Alice',
'Email': 'alice@example.com'
})
Explanation
Gets a reference to the Users table.
table = dynamodb.Table('Users')
Calls put_item() to insert a new record.
table.put_item(Item={...})
Defines the UserID, Name, and Email.
'UserID': '123', 'Name': 'Alice', 'Email': '
alice@example.com
'
Ensures atomicity for single-item inserts.
put_item()
Example 2: Batch Insert Multiple Items
with table.batch_writer() as batch:
batch.put_item(Item={'UserID': '124', 'Name': 'Bob'})
batch.put_item(Item={'UserID': '125', 'Name': 'Charlie'})
Explanation
Uses batch_writer() for efficient writes.
with table.batch_writer() as batch:
Inserts multiple UserID entries in one call.
batch.put_item(Item={'UserID': '124', 'Name': 'Bob'})
Reduces API call overhead.
batch.put_item(Item={'UserID': '125', 'Name': 'Charlie'})
Helps when inserting many records quickly.
batch_writer()
Example 3: Insert with Condition
table.put_item(
Item={'UserID': '126', 'Name': 'Dave'},
ConditionExpression="attribute_not_exists(UserID)"
)
Explanation
Inserts only if UserID does not exist.
ConditionExpression="attribute_not_exists(UserID)"
Prevents overwriting existing users.
put_item(Item={...})
Ensures data consistency for unique keys.
ConditionExpression
Raises an error if UserID exists.
attribute_not_exists(UserID)
Example 4: Insert with Auto Timestamp
import time
table.put_item(Item={
'UserID': '127',
'Name': 'Eve',
'CreatedAt': int(time.time())
})
Explanation
Uses time.time() to store timestamps.
int(time.time())
Ensures each record has a CreatedAt field.
'CreatedAt': int(time.time())
Helps track when a record was inserted.
CreatedAt
Stores timestamps in UNIX format.
time.time()
3. Fetching Data
Example 1: Get a Single Item
response = table.get_item(Key={'UserID': '123'})
print(response.get('Item'))
Explanation
Retrieves a record by UserID.
table.get_item(Key={'UserID': '123'})
Uses get() to avoid key errors.
response.get('Item')
Prints the retrieved user data.
print(response.get('Item'))
Returns
None
if UserID not found.get_item()
Example 2: Query Data by Sort Key
response = table.query(
KeyConditionExpression="CustomerID = :cid",
ExpressionAttributeValues={":cid": "CUST123"}
)
Explanation
Queries CustomerID = 'CUST123'.
KeyConditionExpression="CustomerID = :cid"
Uses ExpressionAttributeValues to pass parameters.
":cid": "CUST123"
Returns multiple matching records.
table.query()
More efficient than scanning the entire table.
query()