Search code examples
amazon-web-servicesamazon-dynamodbttl

How can I Query on TTL in dynamoDB?


I have setup a TTL attribute in my dynamoDB table. when i push records in a get the current date (using js sdk in node) and add a value to it (like 5000). It is my understanding that when that date is reached aws will purge the record but only within 48 hours. during that time the record could be returned as the result of a query. I want to filter out the expired items so that if they are expired but not deleted they won't be returned as part of the query. here is what i am using to try to do that:

var epoch = Math.floor(Date.now() / 1000);
console.log("ttl epoch is ", epoch);
var queryTTLParams = {
    TableName : table,
    KeyConditionExpression: "id = :idval",
    ExpressionAttributeNames:{
        "#theTTL": "TTL"
    },
    FilterExpression: "#theTTL < :ttl",
    ExpressionAttributeValues: {
        ":idval": {S: "1234"},
        ":ttl": {S: epoch.toString()}
    }
};

i do not get any results. I believe the issue has to do with the TTL attribute being a string and me trying to do a < on it. But i didn't get to decide on the datatype for the TTL field - aws did that for me. How can i remedy this?


Solution

  • According to the Enabling Time to Live AWS documentation, the TTL should be set to a Number attribute:

    TTL is a mechanism to set a specific timestamp for expiring items from your table. The timestamp should be expressed as an attribute on the items in the table. The attribute should be a Number data type containing time in epoch format. Once the timestamp expires, the corresponding item is deleted from the table in the background.

    You probably just need to create a new Number attribute and set the TTL attribute to that one.