amazon-web-servicesamazon-dynamodbaws-cdkdynamodb-queries

Dynamodb scan "Float types are not supported. Use Decimal types instead" when filtering on decimal


I'm stumped on this one..

this is my scan:

        response = table.scan(
        FilterExpression=Attr('ttl').gte(Decimal(time.time()-900)) & Attr('SessionStatus').eq('failed'))

Yet when I run it, I get error: Float types are not supported. Use Decimal types instead.

What am I doing wrong?


Solution

  • In DynamoDB, float types are not directly supported, and it's recommended to use Decimal types instead to maintain precision when working with decimal numbers. Try the code below instead

    import boto3
    import time
    from boto3.dynamodb.conditions import Attr
    from decimal import Decimal
    
    # Initialize DynamoDB client
    dynamodb_client = boto3.client('dynamodb', region_name='YOUR_REGION')
    
    # Function to perform the scan
    def scan_with_filter():
        try:
            # Calculate the time threshold for 15 minutes ago
            time_threshold = Decimal(str(time.time() - 900))  # 900 seconds = 15 minutes
    
            # Define scan parameters with the updated FilterExpression
            scan_params = {
                'TableName': 'YOUR_TABLE_NAME',
                'FilterExpression': Attr('ttl').gte(time_threshold) & Attr('SessionStatus').eq('failed')
            }
    
            response = dynamodb_client.scan(**scan_params)
    
            # Process scanned items
            items = response.get('Items', [])
            print("Scanned items:", items)
        except Exception as e:
            print("Error scanning DynamoDB table:", e)
    
    # Perform the scan with the specified FilterExpression
    scan_with_filter()