如何使用Python扫描特定键的dynamoDB表?

时间:2018-03-08 17:25:52

标签: python lambda aws-lambda amazon-dynamodb

我正在尝试扫描列名为S3KeyID的值,我正在寻找值“newkey”。
当我在测试中运行它时,它扫描dynamoDB表中的所有3个项目,它找到3个结果,没有匹配。

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

见结果:

Items": [],
  "Count": 0,
  "ScannedCount": 3,

1 个答案:

答案 0 :(得分:1)

我想这样做会更好:

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

Read the docs了解更多示例。这是我的灵感:

  

同样,您可以根据项目的属性扫描表格。例如,这会扫描年龄小于27的所有用户:

response = table.scan(
    FilterExpression=Attr('age').lt(27)
)
items = response['Items']
print(items)