Search code examples
amazon-web-servicesamazon-dynamodbboto3

How to set Time to live in dynamodb item


I am trying to add items in dynamodb in batch. My table consists of composite primary key i.e. a combination of primary key and sort key. I have enabled time to live on my table but metrics for deletedItemsCount is showing no change.

Following is my code :-

def generate_item(data):
    item = {
        "pk": data['pk'],
        "ttl": str(int(time.time())), # current time set for testing
        "data": json.dumps({"data": data}),
        "sk": data['sk']
    }

    return item

def put_input_data(input_data, table_name):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(table_name)

    data_list = input_data["data"]

    try:
        with table.batch_writer() as writer:
            for index, data in enumerate(data_list):
                writer.put_item(Item=generate_item(data))
    except ClientError as exception_message:
        raise

On querying the table I can see item is getting added into the table, but graph for deletedItemsCount shows no change.

Can someone point where am I going wrong ? Would appreciate any hint.

Thanks


Solution

  • looks like your ttl attribute is a String, but...

    The TTL attribute’s value must be a Number data type. For example, if you specify for a table to use the attribute name expdate as the TTL attribute, but the attribute on an item is a String data type, the TTL processes ignore the item.

    Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-before-you-start.html#time-to-live-ttl-before-you-start-formatting

    Hope that resolves your issue.