如何在 Amazon DynamoDB 中实施分页?
上次更新日期:2022 年 8 月 12 日
当我尝试使用“查询”或“扫描”操作从 Amazon DynamoDB 表中获取项目时,响应返回不完整的结果。
解决方案
在以下情况下,会出现此问题:
- 在响应中,您的初次“扫描”或“查询”操作包含 LastEvaluatedKey。
- 对于下一个请求,您没有将此密钥用作 ExclusiveStartKey 执行后续操作。
您可以通过为 DynamoDB 表实施分页来解决此问题。分页是在之前的请求不完整时发送后续请求以继续的过程。DynamoDB 中的“查询”或“扫描”操作可能会返回不完整的结果,需要后续请求才能获得整个结果集。这是因为 DynamoDB 会对“查询”或“扫描”操作的结果进行分页,并在单个操作中最大 返回1MB 的数据。这是 DynamoDB 中的硬性限制。借助分页,“扫描”和“查询”操作的结果将被分为数据大小不超过 1 MB 的页面。
要对结果进行分页并以一次一页对这些结果进行检索,请检查“扫描”或“查询”操作的低级别结果,以查看结果是否包含 LastEvaluatedKey 元素。您可以使用具有相同参数的另一个“扫描”或“查询”操作来获取初次请求的剩余结果,但需使用 LastEvaluatedKey 值作为 ExclusiveStartKey 参数。如果结果不包含 LastEvaluatedKey 值,则没有要检索的项目。
有关更多信息,请参阅对表查询结果进行分页以及对结果进行分页。
要使用 LastEvaluatedKey 在 Boto3 中实施分页,请使用以下示例代码:
from __future__ import print_function # Python 2/3 compatibility
import boto3
from botocore.exceptions import ClientError
# Create Client
session = boto3.session.Session()
dynamoDbClient = session.client('dynamodb')
table_name = 'AmazonBins'
# Track number of Items read
item_count = 0
try:
# Get the first 1MB of data
response = dynamoDbClient.scan(
TableName=table_name
)
except ClientError as error:
print("Something went wrong: ")
print(error.response['ResponseMetadata'])
# Track number of Items read
item_count += len(response['Items'])
# Paginate returning up to 1MB of data for each iteration
while 'LastEvaluatedKey' in response:
try:
response = dynamoDbClient.scan(
TableName=table_name,
ExclusiveStartKey=response['LastEvaluatedKey']
)
# Track number of Items read
item_count += len(response['Items'])
except ClientError as error:
print("Something went wrong: ")
print(error.response['ResponseMetadata'])
print("Total number of items found: {}".format(item_count))