Paginating a DynamoDB query in boto3

2019-06-20 10:04发布

问题:

How can I loop through all results in a DynamoDB query, if they span more than one page? This answer implies that pagination is built into the query function (at least in v2), but when I try this in v3, my items seem limited:

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
fooTable = dynamodb.Table('Foo')
response = fooTable.query(
    KeyConditionExpression=Key('list_id').eq('123')
)

count = 0

for i in response['Items']:
    count += 1

print count # Prints a subset of my total items

回答1:

ExclusiveStartKey is the name of the attribute which you are looking for. Use the value that was returned for LastEvaluatedKey in the previous operation.

The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed.

http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Client.query