Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript query last items in dynamodb from aws lambda

So I have a dynamodb table with a primary key ID and a secondary key Time which is a number/timestamp. Now I want to query the latest record of a particular ID. I tried to construct the parameters like this but don't know how to move forward to query the item with the largest Time.

function get_snapshot(id, callback){
    let params = {
        TableName: "Table1",
        KeyConditionExpression: "ID = :id and Time ", // here I stuck
        ExpressionAttributeValues: {
        ":id": id
        }
    }; 
    docClient.query(params, function(err, data){
        ... // process the fetched item here
    })
}

I'm quite new to this field. There could be a lot of rookie mistakes. Any help is appreciated.

like image 722
Kevin Fang Avatar asked Sep 17 '25 17:09

Kevin Fang


1 Answers

You don't actually need the Time attribute for your query. If you want to get the 10 latest items, for example, your query params should look like this:

let params = {
    TableName: "Table1",
    KeyConditionExpression: "ID = :id",
    ExpressionAttributeValues: {
        ":id": id
    },
    ScanIndexForward: false,
    Limit: 10
}; 

ScanIndexForward: false tells DynamoDB that it should return results starting with the highest sort key value. Limit: 1 tells DynamoDB that you only want to get the first 10 results.

like image 195
Matthew Pope Avatar answered Sep 19 '25 07:09

Matthew Pope