How can I scan a dynamoDB table with Python for a specific key?

12,234

I guess that works better:

response = table.scan(
    FilterExpression = Attr('S3KeyID').eq('newkey')
)

Read the docs for more examples. Here is my inspiration:

Similarly you can scan the table based on attributes of the items. For example, this scans for all the users whose age is less than 27:

response = table.scan(
    FilterExpression=Attr('age').lt(27)
)
items = response['Items']
print(items)
Share:
12,234
user2849976
Author by

user2849976

Updated on June 14, 2022

Comments

  • user2849976
    user2849976 almost 2 years

    I am trying to scan for a value with column name S3KeyID and I'm looking for the value "newkey".
    When I run this in test, it scans all 3 items in the dynamoDB Table and it finds 3 results and no matches.

    import boto3
    import json
    import decimal
    import calendar
    import datetime
    from boto3.dynamodb.conditions import Key, Attr
    
    def lambda_handler(event, context):
    
        StartDateTime = datetime.datetime.now() - datetime.timedelta(minutes=10000)
        EndDateTime = datetime.datetime.now()
    
    
        # Helper class to convert a DynamoDB item to JSON.
        class DecimalEncoder(json.JSONEncoder):
            def default(self, o):
                if isinstance(o, decimal.Decimal):
                    return str(o)
                return super(DecimalEncoder, self).default(o)
    
        dynamodb = boto3.resource('dynamodb')
    
        table = dynamodb.Table('Overwatch')
    
        print("Overwatch old messages")
    
        response = table.scan(
                #ExpressionAttributeNames = {'ST' : 'S3KeyID'},
    
                FilterExpression = "S3KeyID = :key",
    
                ExpressionAttributeValues =
                {   #":dateStart": {"S": StartDateTime},
                    #":dateEnd": {"S": EndDateTime},
                    ":key" : {"S" : "newkey"}
        #            ":S3KeyID : 1222433"
                }
    
                #ProjectionExpression="S3KeyID"
        )
    
        for i in response[u'Items']:
            print(json.dumps(i, cls=DecimalEncoder))
        return response
    

    See result:

    Items": [],
      "Count": 0,
      "ScannedCount": 3,
    
  • user2849976
    user2849976 about 6 years
    Thanks Costin. that worked for me. I commented out all the ExpressionAttributeValues with it
  • user2849976
    user2849976 about 6 years
    Do you know if .lt works for a date saved as a string?
  • Costin
    Costin about 6 years
    I do not know if .lt() works for strings, but give it a try and let us know. :) (I do everything in nodejs on aws)
  • user2849976
    user2849976 about 6 years
    Ah, I actually translated the datetime to epoch and then just treated it as an int and did it that way, works great!