DynamoDB is inherently structured around hash-based partitions. Because of this, it is not designed to support queries like "fetch all products starting with the letter D sorted alphabetically." Attempting to do this with a standard scan is extremely slow and expensive.
If your storefront app requires an A-Z directory index for SEO purposes, you must structure your data models specifically to support this query pattern.
1. Composite Partition-Sort Keys
To group items alphabetically, we create a DynamoDB table with a Partition Key (PK) storing the first letter of the product name (e.g., letter#D) and a Sort Key (SK) storing the full product name. Since DynamoDB stores items within a partition sorted by their sort key, we can query all items starting with D in perfect alphabetical order:
# Querying alphabetical lists in Python
def get_parts_by_letter(table_name, letter, limit=50, start_key=None):
params = {
"TableName": table_name,
"KeyConditionExpression": "PK = :pk",
"ExpressionAttributeValues": {":pk": {"S": f"letter#{letter.upper()}"}},
"Limit": limit
}
if start_key:
params["ExclusiveStartKey"] = start_key
return dynamodb.query(**params)
2. The Available Letters Table
To avoid querying empty partitions (e.g., searching for products starting with X when none exist), we maintain a secondary, lightweight lookup table goseanto-available-part-number-first-letters. The storefront reads this table to render active links for letters, preventing dead-ends for users.