AWS, Cloud

AWS DynamoDB – get the latest item

One of the latest issue which I met with AWS was getting the latest item (record) from DynamoDB. In my case data are base on the the hash key and range key. The range key is date (and in my case it is guarantee that I will often get the data). To avoid too many read operations (scan entire table), we scan from the newest record (ScanIndexForward = false) and limit the number of records to 1. I did not need consistent read as it is “cheaper” option.

 
 var query = new QueryRequest
 {
    ProjectionExpression = "DateTimeUtc"
    KeyConditionExpression = "key = :keyValue and DateTimeUtc >= :dt",
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>;
    {
        { ":patientGuid", new AttributeValue(patientGuid) },
        { ":dt", new AttributeValue 
            { S = DateTime.UtcNow.AddSeconds(-30)
                .ToString(dtFormat, CultureInfo.InvariantCulture) }
        }
    },
    ScanIndexForward = false,
    ConsistentRead = false,
    Limit = 1,
    TableName = "tableName"
 };

BTW before you will create table, check if name is allowed. There is quite long list of forbidden column names (e.g. DateTime) – you can create a table with column with such name but you will not be able to query this table programmatically.

1 Comment

  1. You could still query a table that uses forbidden column names, but you need to create aliases using ExpressionAttributeNames and put a “#” in front of it. For example:

    Key: {
    “#date”: “2016-11-11T17:21:07.5272333Z”,
    “accountid”: “12345”
    },
    ExpressionAttributeNames: {
    “#date”: “date”
    }

Leave a Reply

Your email address will not be published. Required fields are marked *