Update dynamodb items programatically

Today, I wanted to update all dynamodb items and couldn't find a handy example in AWS documentation.  Below is a handy script that I created to update all the dynamodb table rows with current time stamp using python


from __future__ import print_function # Python 2/3 compatibility import boto3 import json import decimal from boto3.dynamodb.conditions import Key, Attr import datetime, time row = 0 table_name = 'table' dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(table_name) # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) def updateItem(item): global row response = table.update_item( Key=item, UpdateExpression='SET #s = :updated', ExpressionAttributeNames={ '#s' : 'updated' }, ExpressionAttributeValues={ ':updated' : datetime.datetime.now().replace(microsecond=0).isoformat() + 'Z' } ) row += 1 #print("response: ", response) print ("row # ", row, " updated succesfully") pe = "#k" ean = { "#k": "id", } response = table.scan( ProjectionExpression=pe, ExpressionAttributeNames=ean ) for item in response['Items']: #print(json.dumps(i, cls=DecimalEncoder)) try: updateItem(item) except Exception as e: print(e) #continue scanning if we have more data in the table, because scan can retrieve a maximum of 1MB of data while 'LastEvaluatedKey' in response: response = table.scan( ProjectionExpression=pe, ExpressionAttributeNames= ean, ExclusiveStartKey=response['LastEvaluatedKey'] ) for items in response['Items']: try: print(items) updateItem(items) except Exception as e: print(e) print(table_name, " updated completed")

Comments

Popular posts from this blog

Validate Cognito tokens in Kong

Tracing Requests in AWS Serverless Applications

Leveraging AWS Elasticsearch