Your DynamoDB table is keyed by userId. Now product wants "all orders with status PENDING", or "find a user by email". You try:
await ddb.query({ TableName: "Orders", KeyConditionExpression: "status = :s", ... })
// ValidationException: Query condition missed key schema element: userId
So you switch to Scan with a FilterExpression. It works in development, then takes 40 seconds and costs a fortune in production. Here's how querying on non-key attributes is supposed to work in DynamoDB.
Query vs. Scan
Queryneeds an equality condition on the partition key and can optionally narrow the sort key (=,<,>,BETWEEN,begins_with). It reads only the matching item collection, so it's fast and cheap at any table size.Scanreads every item in the table, 1 MB per page, and charges for everything it reads.
A FilterExpression doesn't change that. Filters are applied after items are read, so you pay read capacity for every scanned item, including the 99.9% the filter throws away. Filters are only for trimming a Query result that's already small.
(PartiQL's SELECT … WHERE status = 'PENDING' without the key is the same full scan, just in SQL syntax.)
The fix: design keys for your access patterns
DynamoDB flips the relational approach. You list your queries first and then shape keys and indexes so that every query is a key lookup.
Global secondary indexes (GSIs)
A GSI is a second copy of the data with a different partition key and sort key:
ddb.({
: ,
: ,
: ,
: { : },
: { : , : },
});
