put_item
- write one record(one item) into a table
- If put an item with the same hash key and same range key:
PutItemwill overwrite/replace the existing item by default.- Not get an error unless you explicitly prevent overwrites.
Add attributes put_item
if bucket_name as HASH key, must add items to store records.
dynamodb = boto3.client("dynamodb", region_name="us-west-2")
dynamodb.put_item(
TableName="S3-object-size-history",
Item={
"bucket_name": {"S": "TestBucket"}, # PK
"computed_at": {"N": str(int(time.time() * 1000))}, # SK
"total_size_bytes": {"N": "123456"}, # extra attribute
"total_objects": {"N": "42"}, # extra attribute
"note": {"S": "triggered by s3 event"} # extra attribute
}
)use to create a metadata to store max
meta_key = "__MaxSize__"
def put_maxitem(tablename, key, region):
dynamoDB = boto3.client("dynamodb", region_name=region)
try:
dynamoDB.put_item(
TableName=tablename,
Item={
"bucket_name": {"S": key},
"timestamp": {"N": "0"},
"max_size_bytes": {"N": "0"},
}
)
print(f"--- Put medadata:{key} in {tablename} ---")
except ClientError as e:
print(e)update metadata
- use
UpdateExpression,ConditionExpression,ExpressionAttributeValuesto updateConditionExpressionacts as a gate: DynamoDB evaluates it first.- If it’s true, the update proceeds;
- if it’s false, the update is rejected (e.g.,
ConditionalCheckFailedException).
UpdateExpressiondefines the actual modification- (e.g.,
SET max_size_bytes = :new_size).
- (e.g.,
ExpressionAttributeValuesprovides the concrete values for placeholders like:new_size(including the DynamoDB type, such as"N"for Number).
def update_maxsize(cur_size):
try:
dynamodb.update_item(
TableName=TABLE_NAME,
Key={
"bucket_name": {"S": "__MaxSize__"},
"timestamp": {"N": "0"}
},
UpdateExpression="SET total_size_bytes = :cur_size",
ConditionExpression="attribute_not_exists(total_size_bytes) OR total_size_bytes < :cur_size",
ExpressionAttributeValues={":cur_size": {"N": str(cur_size)}},
)
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
return
raise