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

  1. Connects to DynamoDB using the boto3 library.

    • dynamodb = boto3.resource('dynamodb')
  2. Creates a Users table with a primary key.

    • TableName='Users', KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}]
  3. Defines UserID as a string attribute.

    • AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}]
  4. 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

  1. Creates an Orders table with a primary and sort key.

    • KeySchema=[{'AttributeName': 'OrderID', 'KeyType': 'HASH'}, {'AttributeName': 'CustomerID', 'KeyType': 'RANGE'}]
  2. Defines both keys as string attributes.

    • AttributeDefinitions=[{'AttributeName': 'OrderID', 'AttributeType': 'S'}, {'AttributeName': 'CustomerID', 'AttributeType': 'S'}]
  3. Sort key allows querying by CustomerID.

    • KeyType='RANGE'
  4. 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

  1. Uses the DynamoDB client to interact with AWS.

    • client = boto3.client('dynamodb')
  2. Retrieves a list of all tables.

    • response = client.list_tables()
  3. Prints the table names in the account.

    • print(response['TableNames'])
  4. Helps verify available tables before operations.

    • list_tables()

Example 4: Delete a Table

table = dynamodb.Table('Users')
table.delete()
print("Table deleted")

Explanation

  1. Gets a reference to the Users table.

    • table = dynamodb.Table('Users')
  2. Calls delete() to remove it.

    • table.delete()
  3. Deletes the entire table permanently.

    • delete()
  4. 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

  1. Gets a reference to the Users table.

    • table = dynamodb.Table('Users')
  2. Calls put_item() to insert a new record.

    • table.put_item(Item={...})
  3. Defines the UserID, Name, and Email.

  4. 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

  1. Uses batch_writer() for efficient writes.

    • with table.batch_writer() as batch:
  2. Inserts multiple UserID entries in one call.

    • batch.put_item(Item={'UserID': '124', 'Name': 'Bob'})
  3. Reduces API call overhead.

    • batch.put_item(Item={'UserID': '125', 'Name': 'Charlie'})
  4. 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

  1. Inserts only if UserID does not exist.

    • ConditionExpression="attribute_not_exists(UserID)"
  2. Prevents overwriting existing users.

    • put_item(Item={...})
  3. Ensures data consistency for unique keys.

    • ConditionExpression
  4. 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

  1. Uses time.time() to store timestamps.

    • int(time.time())
  2. Ensures each record has a CreatedAt field.

    • 'CreatedAt': int(time.time())
  3. Helps track when a record was inserted.

    • CreatedAt
  4. 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

  1. Retrieves a record by UserID.

    • table.get_item(Key={'UserID': '123'})
  2. Uses get() to avoid key errors.

    • response.get('Item')
  3. Prints the retrieved user data.

    • print(response.get('Item'))
  4. 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

  1. Queries CustomerID = 'CUST123'.

    • KeyConditionExpression="CustomerID = :cid"
  2. Uses ExpressionAttributeValues to pass parameters.

    • ":cid": "CUST123"
  3. Returns multiple matching records.

    • table.query()
  4. More efficient than scanning the entire table.

    • query()