2023-03-28 23:42:51+00:00

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.

Composite Sort Keys (`GSI1PK` / `GSI1SK`) for Cursor Pagination

Encode the last evaluated ExclusiveStartKey as an URL-safe Base64 cursor token signed with HMAC-SHA256 so clients can paginate millions of DynamoDB items in $O(1)$ time.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs