Created
June 1, 2019 14:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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