Skip to content

Instantly share code, notes, and snippets.

@eduardovra
Created June 1, 2019 14:47
Show Gist options
  • Save eduardovra/a4f65b1f7ca7d1ede1f861d002b971e6 to your computer and use it in GitHub Desktop.
Save eduardovra/a4f65b1f7ca7d1ede1f861d002b971e6 to your computer and use it in GitHub Desktop.
A function that handles pagination on a DynamoDB query operation, returning an iterator
import boto3
from boto3.dynamodb.conditions import Key
def query_dynamodb_table(table, params):
"""
Perform a Query operation and handles pagination automatically,
returning an iterator.
This will work for Scan operations too.
Tested on python 3.6
"""
response = table.query(**params)
for item in response['Items']:
yield item
while 'LastEvaluatedKey' in response:
response = table.query(**{
**params, 'ExclusiveStartKey': response['LastEvaluatedKey']
})
for item in response['Items']:
yield item
table = boto3.resource('dynamodb').Table('ddb_table_name')
params = {'KeyConditionExpression': Key('PK').eq('my_partition_key')}
for item in query_dynamodb_table(table, params):
print(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment