dynamo-db
  1. dynamo-db-put-operation

DynamoDB Conditional Writes - Put Operation

Syntax

response = table.put_item(
  Item={
       "primary-key": value1,
       "attribute1": value2,
       "attribute2": value3,
        ...
     },
  ConditionExpression='condition-expression'
)

Example

response = table.put_item(
    Item={
        'year': 2022,
        'title': 'The Best Movie Ever',
        'info': {
            'plot': 'An incredible film about everything!',
            'rating': 10
        }
    },
    ConditionExpression="attribute_not_exists(year) AND attribute_not_exists(title)"
)

Output

Upon successful execution, the Put operation will return a response object with the following information:

  • ConsumedCapacity: the number of Capacity Units consumed by the operation
  • ItemCollectionMetrics: information about item collections, if any, that were affected by the operation

Explanation

The Put operation in DynamoDB is used to insert a new item into a table. However, sometimes it is necessary to conditionally write data to avoid overwriting existing data or to ensure that a certain condition is met before the write occurs. This is where Conditional Writes come into play.

In a Put operation with a ConditionExpression, the write will only succeed if the condition evaluates to true. In the example above, if there is already an item in the table with the same values for year and title, the Put operation will fail and the item will not be inserted.

Use

Use the Put operation with Conditional Writes when you need to conditionally write data to DynamoDB, ensuring that certain conditions are met before the write occurs. Some use cases for Conditional Writes include avoiding overwriting existing data, checking for specific attributes before inserting new data, and ensuring that certain values are present before writing.

Important Points

  • The Put operation will overwrite any existing item with the same primary key by default. Use a ConditionExpression to avoid overwriting existing data.
  • When using a ConditionExpression in a Put operation, the write will only succeed if the condition evaluates to true.
  • The Put operation with a ConditionExpression is an idempotent operation, meaning that if the same request is received multiple times, the result will be the same.

Summary

The Put operation in DynamoDB is used to insert a new item into a table. When using Conditional Writes in a Put operation, a ConditionExpression is used to ensure that a certain condition is met before the write occurs. This prevents overwriting existing data and can help maintain data integrity. Use the Put operation with Conditional Writes when you need to conditionally write data to DynamoDB, ensuring that certain conditions are met before the write occurs. Remember that the Put operation is idempotent, so if the same request is received multiple times, the result will be the same.

Published on: