How to get Latest Record from DynamoDB using boto3 Python

0

I am trying to get latest record from dynamo DB Using Lambda function .Please guide me on this.Enter image description here

Table name: HomeDB

asked 3 months ago560 views
2 Answers
2

Your issue is that you use timestamp as a partition key, which will not allow you to retrieve the latest item without knowing the exact time it was written, it's not suggested to ever use a timestamp for a partition key. Below I suggest an alternative data model to suit your needs:

pktimeStamptemperaturepayload
117072111110{some data}
117072162220{some data}
117072173330{some data}
117072144850{some data}

And your Lambda function will look like this:

import boto3
session = boto3.session.Session()
dynamodb = session.resource('dynamodb')
table = dynamodb.Table('HomeDB')
def lambda_handler(event, context):
    response = table.query(
        KeyConditionExpression="#pk= :pk",
        ScanIndexForward=False,
        Limit=1, 
        ExpressionAttributeValues={
              ":pk": 1
        }, 
        ExpressionAttributeNames={
             "#pk":"pk"
        }
     )

    # Other business logic here

More details in this blogpost: https://aws.amazon.com/blogs/database/effective-data-sorting-with-amazon-dynamodb/

profile pictureAWS
EXPERT
answered 3 months ago
  • Good advice from Lee, as always. Thinking outside the box a bit... depending on your use case, there might be an alternate approach you could explore, using DynamoDB Streams.

0

Hi,

This article is probably interesting for what you want to achieve: https://blog.jankosmala.eu/2018/10/20/aws-dynamodb-get-the-latest-item/

Best,

Didier

profile pictureAWS
EXPERT
answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions