Search code examples
amazon-web-servicesamazon-dynamodbdynamodb-queries

Retrieve latest record added to AWS Dynamodb table and display on flask webpage


I am developing a flask website where the I need to retrieve the latest record added to AWS dynamodb table and display the retrieved data on a webpage.

The primary key in my DynamoDB table is timestamp. However to query the record I am using the current date only. 'currentdate' column is not primary key.

The following is the query I have implemented:

 timestamp1 = datetime.datetime.now()
 timestamp = timestamp1.strftime("%m/%d/%Y")
 table = DynamoDB. Table('smart Irrigation')
      response = table. Scan(
            FilterExpression=Attr('currentdate').eq(timestamp),
            ScanIndexForward=False, Limit=1

        )

However when executing the above query, I am getting the following error message :

ParamValidationError botocore.exceptions.ParamValidationError: Parameter validation failed: Unknown parameter in input: "ScanIndexForward", must be one of: TableName, IndexName, AttributesToGet, Limit, Select, ScanFilter, ConditionalOperator, ExclusiveStartKey, ReturnConsumedCapacity, TotalSegments, Segment, ProjectionExpression, FilterExpression, ExpressionAttributeNames, ExpressionAttributeValues, ConsistentRead


Solution

  • Despite its name ScanIndexForward is not applicable for Scan API.

    They way your data is modeled leaves it very difficult to read your data in the desired way. You should consider remodelling your data.

    Depending on your throughput needs I would use a GSI with a static value as partition key and currentdate as the sort key. That would allow you do so a Query on the index with ScanIndexForward=False and Limit=1 which would return you the latest item.