Debug School

rakesh kumar
rakesh kumar

Posted on

Basics Crud query In Aws DynamoDB

To create a table in AWS DynamoDB
To insert a table in AWS DynamoDB
To update a table in AWS DynamoDB
To Delete a table in AWS DynamoDB
To Perform leftjoin a table in AWS DynamoDB

you can create a DynamoDB table using the AWS SDK for Python (Boto3).

import boto3

# Create DynamoDB client
dynamodb = boto3.client('dynamodb')

# Define the table name and attributes
table_name = 'SensorData'
partition_key = 'SensorID'
sort_key = 'Timestamp'

# Define attribute definitions and key schema
attribute_definitions = [
    {'AttributeName': partition_key, 'AttributeType': 'S'},
    {'AttributeName': sort_key, 'AttributeType': 'S'}
]

key_schema = [
    {'AttributeName': partition_key, 'KeyType': 'HASH'},  # HASH is for partition key
    {'AttributeName': sort_key, 'KeyType': 'RANGE'}      # RANGE is for sort key (optional)
]

# Define provisioned throughput settings (adjust as needed)
provisioned_throughput = {
    'ReadCapacityUnits': 5,
    'WriteCapacityUnits': 5
}

# Create the DynamoDB table
response = dynamodb.create_table(
    TableName=table_name,
    AttributeDefinitions=attribute_definitions,
    KeySchema=key_schema,
    ProvisionedThroughput=provisioned_throughput
)

# Wait for the table to be created before proceeding (optional)
dynamodb.get_waiter('table_exists').wait(TableName=table_name)

# Print the response
print(response)
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. table_name is set to 'SensorData'.
  2. partition_key is set to 'SensorID'.
  3. sort_key is set to 'Timestamp' (optional; you can omit this if your table doesn't have a sort key).
  4. attribute_definitions define the types of attributes in the table.
  5. key_schema defines the primary key structure.
  6. provisioned_throughput specifies the provisioned read and write capacity units

After executing this code, you'll get a response indicating that the table creation process has started. The actual table creation may take some time, and you can check the status using the DynamoDB console or programmatically.

The output will be a response from the create_table operation, providing information about the newly created table, including the table name, status, and other details.

Keep in mind that this example uses provisioned throughput, and you may adjust the capacity units based on your specific requirements. If you want to use on-demand capacity, you can omit the ProvisionedThroughput parameter
output

{
    'TableDescription': {
        'TableName': 'SensorData',
        'TableStatus': 'CREATING',
        'ProvisionedThroughput': {
            'LastIncreaseDateTime': datetime(2022, 1, 1),
            'LastDecreaseDateTime': datetime(2022, 1, 1),
            'NumberOfDecreasesToday': 0,
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5
        },
        'CreationDateTime': datetime(2022, 1, 1),
        'TableSizeBytes': 0,
        'ItemCount': 0,
        'TableArn': 'arn:aws:dynamodb:region:123456789012:table/SensorData',
        # Other table-related information
    }
}
Enter fullscreen mode Exit fullscreen mode

To insert a table in AWS DynamoDB

To insert data into a table in AWS DynamoDB, you can use the put_item operation. Here's an example using the AWS SDK for Python (Boto3):

import boto3
from datetime import datetime

# Create DynamoDB client
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('SensorData')  # Replace with your table name

# Example data to insert
item_to_insert = {
    'SensorID': 'Sensor001',
    'Timestamp': str(datetime.utcnow()),
    'SensorValue': 25.5
}

# Insert data into the table
response = table.put_item(Item=item_to_insert)

# Print the response
print(response)
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. table = dynamodb.Table('SensorData') specifies the DynamoDB table you want to insert data into. Replace 'SensorData' with your actual table name.
  2. item_to_insert is a dictionary containing the attributes and values of the item you want to insert. The 'Timestamp' attribute is set to the current UTC timestamp using datetime.utcnow().
  3. table.put_item(Item=item_to_insert) inserts the item into the table. The output of the put_item operation would typically look like this:
{'ResponseMetadata': {'RequestId': 'abcdef1234567890', 'HTTPStatusCode': 200, 'HTTPHeaders': {...}, 'RetryAttempts': 0}}
Enter fullscreen mode Exit fullscreen mode

This indicates that the operation was successful with an HTTP status code of 200.

After inserting the item, you can verify its presence in the DynamoDB table using the AWS Management Console or by querying the table. If you query the table using a get_item operation, you would see the item you inserted:

# Query the inserted item
response = table.get_item(Key={'SensorID': 'Sensor001', 'Timestamp': item_to_insert['Timestamp']})

# Print the queried item
print(response['Item'])
Enter fullscreen mode Exit fullscreen mode

Keep in mind that the actual output will depend on your specific use case and the data you are inserting. Adjust the attributes and values in the item_to_insert dictionary based on your table's schema.

To update a table in AWS DynamoDB

To edit and update data in a table in AWS DynamoDB, you can use the update_item operation. Here's an example using the AWS SDK for Python (Boto3):

import boto3

# Create DynamoDB client
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('SensorData')  # Replace with your table name

# Example data to update
update_key = {
    'SensorID': 'Sensor001',
    'Timestamp': '2022-01-01T12:00:00'  # Replace with the timestamp of the item to update
}

# Define the update expression and attribute values
update_expression = 'SET SensorValue = :new_value'
expression_attribute_values = {':new_value': 30.0}

# Update data in the table
response = table.update_item(
    Key=update_key,
    UpdateExpression=update_expression,
    ExpressionAttributeValues=expression_attribute_values
)

# Print the response
print(response)
Enter fullscreen mode Exit fullscreen mode

In this example:

table = dynamodb.Table('SensorData') specifies the DynamoDB table you want to update. Replace 'SensorData' with your actual table name.
update_key is a dictionary specifying the primary key attributes (partition key and sort key) of the item you want to update.
update_expression defines the update operation. In this case, it's a simple example using the SET operation to update the SensorValue attribute to a new value.
expression_attribute_values provides the actual values to be used in the update expression.
The output of the update_item operation would typically look like this:

{'ResponseMetadata': {'RequestId': 'abcdef1234567890', 'HTTPStatusCode': 200, 'HTTPHeaders': {...}, 'RetryAttempts': 0}}
Enter fullscreen mode Exit fullscreen mode

This response indicates that the update_item operation was successful with an HTTP status code of 200.

After updating the item, you can verify the changes by querying the table to retrieve the updated item:

# Query the updated item
response = table.get_item(Key=update_key)

# Print the queried item
print(response['Item'])
Enter fullscreen mode Exit fullscreen mode

The output will show the updated item with the changes you applied.

output

{'ResponseMetadata': {'RequestId': 'abcdef1234567890', 'HTTPStatusCode': 200, 'HTTPHeaders': {...}, 'RetryAttempts': 0}}
Enter fullscreen mode Exit fullscreen mode

To Delete a table in AWS DynamoDB

To delete data from a table in AWS DynamoDB, you can use the delete_item operation. Here's an example using the AWS SDK for Python (Boto3):

import boto3

# Create DynamoDB client
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('SensorData')  # Replace with your table name

# Example data to delete
delete_key = {
    'SensorID': 'Sensor001',
    'Timestamp': '2022-01-01T12:00:00'  # Replace with the timestamp of the item to delete
}

# Delete data from the table
response = table.delete_item(Key=delete_key)

# Print the response
print(response)
Enter fullscreen mode Exit fullscreen mode

In this example:

table = dynamodb.Table('SensorData') specifies the DynamoDB table you want to delete data from. Replace 'SensorData' with your actual table name.
delete_key is a dictionary specifying the primary key attributes (partition key and sort key) of the item you want to delete.
The output of the delete_item operation would typically look like this:

{'ResponseMetadata': {'RequestId': 'abcdef1234567890', 'HTTPStatusCode': 200, 'HTTPHeaders': {...}, 'RetryAttempts': 0}}
Enter fullscreen mode Exit fullscreen mode

This response indicates that the delete_item operation was successful with an HTTP status code of 200.

After deleting the item, you can verify its absence by querying the table or using the AWS Management Console.

# Try to query the deleted item
response = table.get_item(Key=delete_key)

# If the item is deleted, the response will not contain 'Item'
if 'Item' not in response:
    print("Item has been deleted.")
else:
    print("Item still exists.")
Enter fullscreen mode Exit fullscreen mode

The output will indicate whether the item has been successfully deleted or if it still exists in the table.

Keep in mind that the actual output may vary based on your specific use case and the data you are deleting. Adjust the delete_key based on the primary key attributes of the item you want to delete.

To Perform leftjoin a table in AWS DynamoDB

Here's an example to illustrate a common scenario where you want to retrieve items from two DynamoDB tables and emulate a LEFT JOIN operation. In this example, let's consider two tables: Users and Orders.

import boto3

# Create DynamoDB client
dynamodb = boto3.resource('dynamodb')

# Define table names
users_table = dynamodb.Table('Users')
orders_table = dynamodb.Table('Orders')

# Perform a scan on the Users table
users_response = users_table.scan()

# Iterate through each user
for user_item in users_response['Items']:
    user_id = user_item['UserID']

    # Perform a query on the Orders table for the current user
    orders_response = orders_table.query(
        KeyConditionExpression='UserID = :user_id',
        ExpressionAttributeValues={':user_id': user_id}
    )

    # Print the user information and associated orders
    print(f"User: {user_item}")
    print(f"Orders: {orders_response['Items']}")
    print("---------------")
Enter fullscreen mode Exit fullscreen mode

In this example:

The code scans the Users table to retrieve all users.
For each user, it queries the Orders table using the user's ID (UserID).
The output includes information about each user and their associated orders.
Keep in mind that this approach may not be as efficient as a relational database JOIN operation, and it depends on your specific use case. Additionally, you might need to consider factors like data distribution and volume.

Remember to replace 'Users' and 'Orders' with your actual table names, and adapt the code according to your specific schema and requirements.

output

Users Table:

[
    {"UserID": "user001", "Username": "John Doe"},
    {"UserID": "user002", "Username": "Jane Doe"}
]
Enter fullscreen mode Exit fullscreen mode

Orders Table:

[
    {"OrderID": "order001", "UserID": "user001", "Product": "ProductA"},
    {"OrderID": "order002", "UserID": "user001", "Product": "ProductB"},
    {"OrderID": "order003", "UserID": "user002", "Product": "ProductC"}
]
Enter fullscreen mode Exit fullscreen mode

The output of the provided code would be:

User: {'UserID': 'user001', 'Username': 'John Doe'}
Orders: [{'OrderID': 'order001', 'UserID': 'user001', 'Product': 'ProductA'}, {'OrderID': 'order002', 'UserID': 'user001', 'Product': 'ProductB'}]
---------------

User: {'UserID': 'user002', 'Username': 'Jane Doe'}
Orders: [{'OrderID': 'order003', 'UserID': 'user002', 'Product': 'ProductC'}]
---------------
Enter fullscreen mode Exit fullscreen mode

Explanation:

The code scans the Users table and retrieves information about each user.
For each user, it queries the Orders table to retrieve orders associated with that user.
The output includes user information and associated orders.

Top comments (0)