DynamoDB Query in Node.js (AWS SDK v3)
Query reads every item that shares one partition key, optionally narrowing by the sort key. In AWS SDK v3 you send a QueryCommand whose KeyConditionExpression names the keys and ExpressionAttributeValues supplies the marshalled values.
Code
import {DynamoDBClient, QueryCommand} from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({region: 'us-east-1'});
async function querySongsByArtist(artist) {
const items = [];
let lastEvaluatedKey;
do {
const response = await client.send(
new QueryCommand({
TableName: 'Music',
KeyConditionExpression: 'Artist = :artist AND begins_with(SongTitle, :prefix)',
ExpressionAttributeValues: {
':artist': {S: artist},
':prefix': {S: 'C'}
},
// false = descending (newest/highest sort key first)
ScanIndexForward: true,
Limit: 100,
ExclusiveStartKey: lastEvaluatedKey
})
);
items.push(...(response.Items ?? []));
lastEvaluatedKey = response.LastEvaluatedKey;
} while (lastEvaluatedKey);
console.log(`Found ${items.length} songs`);
return items;
}
querySongsByArtist('Arturo Sandoval');Explanation
KeyConditionExpression— must include an equality on the partition key (Artist = :artist) and may add one sort-key condition (=,<,<=,>,>=,BETWEEN, orbegins_with). You cannotScan-style filter here.ExpressionAttributeValues— the:placeholder→ value map, in low-level format ({ S: ... }).ScanIndexForward—true(default) returns items in ascending sort-key order;falsereverses it.Limit— caps items per page, evaluated before anyFilterExpression.- Pagination — a single
Queryreturns at most 1 MB. When more remains,LastEvaluatedKeyis set; feed it back asExclusiveStartKeyuntil it'sundefined. The loop above collects the full result set. - To query a secondary index, add
IndexName: "...".
Do it visually
The DynamoDB Expression Builder builds the KeyConditionExpression + ExpressionAttributeValues for you and copies the code — no hand-typed placeholders.
To run queries against real tables in a GUI — key-condition form, paginated results grid, copy the generated SDK v3 code — download DynoTable.
Related guides
- Query vs. Scan — why
Queryis the right default. - Key condition expressions — every legal partition/sort-key operator.