AWS. Lesson 3. Dynamodb Key Types.

Top 10 Key Types in DynamoDB

Each KeyType has two code examples with detailed explanations.


1. HASH (Partition Key)

Example 1: Simple Primary Key

table = dynamodb.create_table(
    TableName='Users',
    KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}],
    AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}],
    ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)

Explanation

  1. Creates a table with UserID as the primary key.

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

    • AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}]
  3. Ensures high performance with a single key.

    • ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
  4. Ideal for lookup operations using UserID.

    • TableName='Users'

Example 2: Insert Data

table.put_item(Item={'UserID': 'U001', 'Name': 'Alice'})

Explanation

  1. Inserts a new user with UserID as the key.

    • Item={'UserID': 'U001', 'Name': 'Alice'}
  2. Allows fast lookups using the key.

    • table.put_item(Item={...})
  3. Ensures uniqueness of UserID.

    • UserID='U001'
  4. Used for primary key-based queries.

    • table.get_item(Key={'UserID': 'U001'})

2. RANGE (Sort Key)

Example 1: Composite 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. Uses OrderID as the partition key.

    • {'AttributeName': 'OrderID', 'KeyType': 'HASH'}
  2. Uses CustomerID as the sort key.

    • {'AttributeName': 'CustomerID', 'KeyType': 'RANGE'}
  3. Allows ordering data by CustomerID.

    • KeySchema=[..., {'AttributeName': 'CustomerID', 'KeyType': 'RANGE'}]
  4. Enables efficient range queries.

    • ProvisionedThroughput

Example 2: Query with Sort Key

response = table.query(
    KeyConditionExpression="OrderID = :oid AND CustomerID > :cid",
    ExpressionAttributeValues={":oid": "ORD123", ":cid": "CUST100"}
)

Explanation

  1. Queries all orders of OrderID = ORD123.

    • KeyConditionExpression="OrderID = :oid"
  2. Filters by CustomerID greater than CUST100.

    • "CustomerID > :cid"
  3. Uses ExpressionAttributeValues to bind values.

    • {":oid": "ORD123", ":cid": "CUST100"}
  4. Retrieves sorted, paginated results.

    • table.query()

3. LOCAL SECONDARY INDEX (LSI)

Example 1: Create LSI

table = dynamodb.create_table(
    TableName='Orders',
    KeySchema=[{'AttributeName': 'OrderID', 'KeyType': 'HASH'}],
    AttributeDefinitions=[
        {'AttributeName': 'OrderID', 'AttributeType': 'S'},
        {'AttributeName': 'OrderDate', 'AttributeType': 'S'}
    ],
    LocalSecondaryIndexes=[
        {
            'IndexName': 'OrderDateIndex',
            'KeySchema': [
                {'AttributeName': 'OrderID', 'KeyType': 'HASH'},
                {'AttributeName': 'OrderDate', 'KeyType': 'RANGE'}
            ],
            'Projection': {'ProjectionType': 'ALL'}
        }
    ],
    ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)

Explanation

  1. Creates a table with OrderID as HASH key.

    • KeySchema=[{'AttributeName': 'OrderID', 'KeyType': 'HASH'}]
  2. Defines OrderDate as the LSI sort key.

    • 'KeySchema': [{'AttributeName': 'OrderID', 'KeyType': 'HASH'}, {'AttributeName': 'OrderDate', 'KeyType': 'RANGE'}]
  3. Enables alternate sorting by OrderDate.

    • 'IndexName': 'OrderDateIndex'
  4. Allows faster queries on OrderDate.

    • 'Projection': {'ProjectionType': 'ALL'}

Example 2: Query Using LSI

response = table.query(
    IndexName='OrderDateIndex',
    KeyConditionExpression="OrderID = :oid AND OrderDate > :odate",
    ExpressionAttributeValues={":oid": "ORD123", ":odate": "2024-01-01"}
)

Explanation

  1. Queries using the LSI OrderDateIndex.

    • IndexName='OrderDateIndex'
  2. Filters records after 2024-01-01.

    • "OrderDate > :odate"
  3. Uses ExpressionAttributeValues for parameters.

    • {":oid": "ORD123", ":odate": "2024-01-01"}
  4. Retrieves sorted results efficiently.

    • table.query()

4. GLOBAL SECONDARY INDEX (GSI)

Example 1: Create GSI

table.update(
    AttributeDefinitions=[
        {'AttributeName': 'CustomerID', 'AttributeType': 'S'},
        {'AttributeName': 'OrderDate', 'AttributeType': 'S'}
    ],
    GlobalSecondaryIndexUpdates=[
        {
            'Create': {
                'IndexName': 'CustomerIndex',
                'KeySchema': [
                    {'AttributeName': 'CustomerID', 'KeyType': 'HASH'},
                    {'AttributeName': 'OrderDate', 'KeyType': 'RANGE'}
                ],
                'Projection': {'ProjectionType': 'ALL'},
                'ProvisionedThroughput': {'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
            }
        }
    ]
)

Explanation

  1. Adds a CustomerIndex on CustomerID.

    • 'KeySchema': [{'AttributeName': 'CustomerID', 'KeyType': 'HASH'}]
  2. Uses OrderDate as the sort key.

    • {'AttributeName': 'OrderDate', 'KeyType': 'RANGE'}
  3. Allows queries by CustomerID.

    • 'IndexName': 'CustomerIndex'
  4. Uses ProvisionedThroughput to scale.

    • 'ProvisionedThroughput': {'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}

Example 2: Query Using GSI

response = table.query(
    IndexName='CustomerIndex',
    KeyConditionExpression="CustomerID = :cid",
    ExpressionAttributeValues={":cid": "CUST123"}
)

Explanation

  1. Queries CustomerIndex using CustomerID.

    • IndexName='CustomerIndex'
  2. Uses KeyConditionExpression for filtering.

    • "CustomerID = :cid"
  3. Uses ExpressionAttributeValues for binding.

    • {":cid": "CUST123"}
  4. Efficiently retrieves customer order history.

    • table.query()

This list includes 4 major KeyTypes (HASH, RANGE, LSI, GSI).

Others KeyTypes are TTL, Streams, Encryption, Capacity Modes, and Transactions?