DynamoDB Query in Python (boto3)
query reads every item that shares one partition key, optionally narrowing by the sort key. With the boto3 resource API you build the condition with the Key helper from boto3.dynamodb.conditions — no hand-written expression strings.
Code
import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.Table("Music")
def query_songs_by_artist(artist):
items = []
kwargs = {
"KeyConditionExpression": Key("Artist").eq(artist)
& Key("SongTitle").begins_with("C"),
"ScanIndexForward": True, # False = descending
"Limit": 100,
}
while True:
response = table.query(**kwargs)
items.extend(response["Items"])
# Paginate: stop when there's no continuation key
if "LastEvaluatedKey" not in response:
break
kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"]
print(f"Found {len(items)} songs")
return items
if __name__ == "__main__":
query_songs_by_artist("Arturo Sandoval")Explanation
Key("Artist").eq(artist)— the required partition-key equality. Chain one sort-key condition with&(.begins_with,.between,.lt,.gt, etc.). TheKeyhelper generates the expression, names, and values for you.ScanIndexForward—True(default) is ascending sort-key order;Falsereverses it.Limit— items per page, applied before anyFilterExpression.- Pagination — one
queryreturns at most 1 MB. When more remains,response["LastEvaluatedKey"]is present; feed it back asExclusiveStartKeyuntil it's gone. The loop collects the whole result set. - Query a secondary index by adding
IndexName="...". - Numeric attributes in the returned items are
decimal.Decimal.
Do it visually
The DynamoDB Expression Builder assembles the key condition and copies runnable code, so you don't hand-write Key(...) chains.
To run queries against real tables in a GUI — key-condition form, paginated grid, copy the generated boto3 code — download DynoTable.
Related guides
- Query vs. Scan — why
queryis the right default. - Key condition expressions — every legal partition/sort-key operator.