Looking for an example of how to Query your DynamoDB Table using Python boto3? This is the article for you.
Its a pretty straightforward to query your dynamodb table using boto3. Lets take a look at an example below.
Note that a github link containing the full code is available at the bottom of this article.
Check out other Python DynamoDB Based Operation Articles here:
First we need to import some dependencies include
boto3 itself, and some dynamodb specific dependencies.
import json import sys import boto3 from boto3.dynamodb.conditions import Key, Attr
Next we need to get a reference to the boto3 dynamodb resource by using
dynamodb = boto3.resource('dynamodb')
In our calling code (in this case I’m using a Lambda Function), we get a reference to our boto3/Dynamo table object.
def lambda_handler(event, context): table = dynamodb.Table('Countries')
We’re ready to perform our query as seen below. We set the
KeyConditionExpression to look for the
Key field CountryName where the value is equal to USA.
Note if you would like to apply any other expressions to your query this is where you would add them.
You can find more boto3 dynamodb query expressions in the boto3 documentation here.
#Make Initial Query response = table.query(KeyConditionExpression=Key('CountryName').eq('USA'))
To parse out and print the results, we can use a simple for loop to read over all records in the response’s
#Extract the Results items = response['Items'] for item in items: countryName = item['CountryName'] state = item['State'] size = sys.getsizeof(item) print(str(queryCount) + ' - ' + countryName + ' - ' + state + ' - ' + str(size))
Adding Pagination to our Boto3 DynamoDB Query
To add pagination, we need to add a value to a field called
When making our initial query, set this value to
null. If after receiving our query response Dynamo returns us a value in the response containing the key
LastEvaluatedKey, it means that there are more results available in the next page. To retrieve all data, we must keep calling this API for all pages until
LastEvaluatedKey is returned as null in the response.
Here’s the code to add pagination:
while 'LastEvaluatedKey' in response: print('---------') key = response['LastEvaluatedKey'] response = table.query(KeyConditionExpression=Key('CountryName').eq('USA'), ExclusiveStartKey=key) items = response['Items'] for item in items: countryName = item['CountryName'] state = item['State'] size = sys.getsizeof(item) print(str(queryCount) + ' - ' + countryName + ' - ' + state + ' - ' + str(size))
You may also enjoy these other articles: