【发布时间】:2022-02-03 07:14:00
【问题描述】:
我正在使用以下代码通过 DynamoDB 查询进行查询和分页:
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)
def run(date: int, start_epoch: int, end_epoch: int):
dynamodb = boto3.resource('dynamodb',
region_name='REGION',
config=Config(proxies={'https': 'PROXYIP'}))
table = dynamodb.Table('XYZ')
response = table.query(
# ProjectionExpression="#yr, title, info.genres, info.actors[0]", #THIS IS A SELECT STATEMENT
# ExpressionAttributeNames={"#yr": "year"}, #SELECT STATEMENT RENAME
KeyConditionExpression=Key('date').eq(date) & Key('uid').between(start_epoch, end_epoch)
)
for i in response[u'Items']:
print(json.dumps(i, cls=DecimalEncoder))
while 'LastEvaluatedKey' in response:
response = table.scan( ##IS THIS INEFFICIENT CODE?
# ProjectionExpression=pe,
# FilterExpression=fe,
# ExpressionAttributeNames=ean,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for i in response['Items']:
print(json.dumps(i, cls=DecimalEncoder))
虽然这段代码有效,但速度非常慢,我担心'response = table.scan' 是这个结果。我的印象是查询比扫描快得多(因为扫描需要整个表迭代)。这段代码是否会导致数据库表的完整迭代?
这可能是一个单独的问题,但是有没有更有效的方法(带有代码示例)来做到这一点?我尝试使用 Boto3 的分页,但我也无法使用查询。
【问题讨论】:
标签: amazon-web-services amazon-dynamodb dynamodb-queries