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

已提问 3 个月前628 查看次数
2 回答
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
专家
已回答 3 个月前
  • 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
专家
已回答 3 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则