Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change data type of column in DynamoDb?

Initially I have inserted integer values hence schema created with column type number, later string values were also inserted in same column. Now I am facing issue while fetching values. Need tho update column type number to string.

like image 491
SaddamK Avatar asked Jan 22 '19 09:01

SaddamK


2 Answers

Well, there are no columns in DynamoDB and even if you consider attributes as columns which they are not, they don't enforce specific type, except for primary key. Therefore you can't change the type of a column.

If you are asking about how to change type of a specific attribute for all items in a table, then you need to run update command on all of the items. DynamoDB unfortunately doesn't support batch update operation, therefore you need to fetch keys of all the items that you need to updated, loop through that list and update each item separately.

like image 92
Matus Dubrava Avatar answered Oct 12 '22 20:10

Matus Dubrava


I recently had to do this. Here is my script that I used:

Assume that 'timestamp' is name of column you need to change from string to number. So here is solution:

import boto3
from boto3.dynamodb.conditions import Key

db_client = boto3.resource('dynamodb', region_name="eu-west-3")
table_res = db_client.Table(TABLE_NAME)



not_finished = True
ret = table_res.scan()
while not_finished:
    for item in ret['Items']:
        if 'timestamp' in item and isinstance(item['timestamp'], str):
            new_item = item
            new_item['timestamp'] = int(float(item['timestamp']))
            print("fixing {}, {} -> {}".format(item['SK'], item['timestamp'], new_item['timestamp']))

            table_res.put_item(Item = new_item)
    if "LastEvaluatedKey" in ret:
        last_key = ret['LastEvaluatedKey']
        ret = table_res.scan(ExclusiveStartKey = last_key)
    else:
        not_finished = False

I do understand you probably don't need this anymore, but I still hope this will help somebody.

like image 42
Andrej Manduch Avatar answered Oct 12 '22 21:10

Andrej Manduch