dynamo-db
  1. dynamo-db-update-operation

Update Operation - DynamoDB CRUD Operations

Syntax

The syntax for updating an item in DynamoDB using the update_item() method is as follows:

response = table.update_item(
    Key={
        'PartitionKey': 'partition_key_value',
        'SortKey': 'sort_key_value'
    },
    UpdateExpression='SET attribute_name = :value',
    ExpressionAttributeValues={
        ':value': 'new_attribute_value'
    }
)

Example

Consider a table named employees with the following attributes:

  • Id: The ID of the employee (Partition Key)
  • Name: The name of the employee
  • Age: The age of the employee
  • Salary: The salary of the employee

To update the salary of an employee with ID '101', the following code can be used:

import boto3

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

# Choose a table
table = dynamodb.Table('employees')

# Update an item
response = table.update_item(
    Key={
        'Id': '101'
    },
    UpdateExpression='SET Salary = :value',
    ExpressionAttributeValues={
        ':value': '50000'
    }
)

print(response)

Output

The output of the update_item() method is a dictionary containing information about the updated item, such as the attributes that were modified and the new values.

{
    'Attributes': {
        'Id': '101',
        'Name': 'John Doe',
        'Age': 30,
        'Salary': '50000'
    }
}

Explanation

The update_item() method is used to update an item in a DynamoDB table. It requires the primary key of the item to be updated, along with an Update Expression that specifies the attributes to be updated and their new values.

In the above example, the Update Expression sets the 'Salary' attribute to a new value of 50000 for an employee with ID '101'. The ':' notation is used to specify the new value for the attribute. The ExpressionAttributeValues dictionary maps each ':' notation to its corresponding value.

Use

The update_item() method is useful when updating specific values in an item in a DynamoDB table. This method can be used to add or remove attributes, update existing attributes, or increment/decrement numerical attribute values.

Important Points

  • The Update Expression must start with the keyword 'SET' when updating attributes.
  • The Partition Key is required to update an item, while Sort Key is optional.
  • The ExpressionAttributeValues dictionary must contain each variable's value used in the Update Expression.

Summary

In summary, the update_item() method is used to update an item in a DynamoDB table. It requires the primary key of the item to be updated, along with an Update Expression that specifies the attributes to be updated and their new values. This method is useful for making changes to specific values in an item.

Published on: