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

gefragt vor 3 Monaten630 Aufrufe
2 Antworten
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
EXPERTE
beantwortet vor 3 Monaten
  • 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
EXPERTE
beantwortet vor 3 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen