Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
like image 415
user2849976 Avatar asked Mar 06 '23 17:03

user2849976


1 Answers

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)
like image 98
Costin Avatar answered Apr 24 '23 21:04

Costin