Query
Use the Query command to retrieve multiple items from DynamoDB based on an item query. This is the Document Builder command for a Query operation.
Basic Usage
Section titled “Basic Usage”Query items by their partition key. This retrieves all items with a matching partition key value.
const todoEntity = new DynamoEntity({ table: parentTable, schema: z.object({ userId: z.string(), todoId: z.string(), title: z.string(), completed: z.boolean(), createdAt: z.string(), }), partitionKey: todo => key('USER', todo.userId), sortKey: todo => key('TODO', todo.todoId),});
// Query all todos for a specific userconst queryCommand = new Query({ key: { userId: '123', },});
const result = await todoEntity.send(queryCommand);console.log(result.items); // Array of all todos for user 123console.log(result.count); // Number of items returnedSort Key Condition
Section titled “Sort Key Condition”Use sortKeyCondition to define conditions on the sort key when querying items.
const query = new Query({ key: { userId: '123', }, sortKeyCondition: { SK: beginsWith('TODO#'), },});
const result = await todoEntity.send(query);const allUsersTodos = result.items;Query Filtering
Section titled “Query Filtering”Use filter to apply additional filtering on non-key attributes.
const orderEntity = new DynamoEntity({ table: parentTable, schema: z.object({ userId: z.string(), orderId: z.string(), status: z.enum(['pending', 'completed', 'canceled']), total: z.number().min(0), createdAt: z.string(), }), partitionKey: order => key('USER', order.userId), sortKey: order => key('ORDER', order.createdAt, 'ORDER_ID', order.orderId),});
const queryCommand = new Query({ key: { userId: '123', }, sortKeyCondition: { SK: beginsWith('ORDER#2024'), }, filter: and( { status: 'completed' }, { total: greaterThan(100) } ),});
const result = await orderEntity.send(queryCommand);Secondary Indexes
Section titled “Secondary Indexes”Query Global Secondary Indexes (GSI) or Local Secondary Indexes (LSI) using the index parameter instead of key.
const todoEntity = new DynamoEntity({ table: parentTable, schema: z.object({ userId: z.string(), todoId: z.string(), status: z.enum(['pending', 'in-progress', 'completed']), dueDate: z.string(), title: z.string(), }), partitionKey: todo => key('USER', todo.userId), sortKey: todo => key('TODO', todo.todoId), globalSecondaryIndexes: { StatusIndex: { partitionKey: todo => key('STATUS', todo.status), sortKey: todo => todo.dueDate, }, },});
const queryCommand = new Query({ index: { StatusIndex: { status: 'in-progress', }, }, sortKeyCondition: { GSI1SK: beginsWith('2024-01'), },});
const result = await todoEntity.send(queryCommand);Projection Queries
Section titled “Projection Queries”Use ProjectedQuery to retrieve only specific attributes from items.
const projectionSchema = z.object({ title: z.string(), completed: z.boolean(),});
const projectedQueryCommand = new ProjectedQuery({ key: { userId: '123', }, projection: ['title', 'completed'], projectionSchema, sortKeyCondition: { SK: beginsWith('TODO#'), },});
const result = await todoEntity.send(projectedQueryCommand);// result.items is typed as Array<{ title: string; completed: boolean; }>console.log(result.items[0]?.title);Query Limiting
Section titled “Query Limiting”Use the limit parameter to restrict the maximum number of items returned by a query.
const queryCommand = new Query({ key: { userId: '123', }, limit: 10,});
const result = await todoEntity.send(queryCommand);// Returns at most 10 itemsconsole.log(result.items.length); // <= 10
if (result.lastEvaluatedKey) { // More items are available const nextQuery = new Query({ key: { userId: '123', }, limit: 10, exclusiveStartKey: result.lastEvaluatedKey, }); const nextResult = await todoEntity.send(nextQuery);}Consistent Reads
Section titled “Consistent Reads”Set consistent to true for strongly consistent query reads.
const queryCommand = new Query({ key: { userId: '123', }, sortKeyCondition: { SK: beginsWith('TODO#'), }, consistent: true,});
const result = await todoEntity.send(queryCommand);Reverse Index Scan
Section titled “Reverse Index Scan”Set reverseIndexScan to true to query items in descending sort key order instead of ascending.
const todoEntity = new DynamoEntity({ table: parentTable, schema: z.object({ userId: z.string(), todoId: z.string(), createdAt: z.iso.datetime(), title: z.string(), }), partitionKey: todo => key('USER', todo.userId), sortKey: todo => todo.createdAt,});
const queryCommand = new Query({ key: { userId: '123', }, reverseIndexScan: true, limit: 10,});
const result = await todoEntity.send(queryCommand);Query Pagination
Section titled “Query Pagination”Document Builder provides automatic pagination support using async generators.
const query = new Query({ key: { userId: '123' }, pageSize: 50, // Items per page});
for await (const page of todoEntity.paginate(query)) { console.log(`Page with ${page.count} items`); processItems(page.items);
// Break early if needed if (page.items.some(item => item.completed)) { break; }}Note the important difference of using paginate() on the entity instead of send().
Query Command Config
Section titled “Query Command Config”The Query command expects the following input config:
{ key: Partial<Schema>; index: { [indexName: string]: Partial<Schema>; }; sortKeyCondition?: Condition; filter?: Condition; limit?: number; selectAttributes?: Select; reverseIndexScan?: boolean; validationConcurrency?: number; exclusiveStartKey?: Partial<Schema>; pageSize?: number; consistent?: boolean; skipValidation?: boolean; timeoutMs?: number; abortController?: AbortController; returnConsumedCapacity?: ReturnConsumedCapacity;}Either key or index is required, but not both.
| Property | Type | Description |
|---|---|---|
key (required) | Partial<Schema> | The primary key of the item to retrieve. If using computed primary keys, only include the attributes used by your key builder functions. Otherwise this should be the attributes that make up the full primary key (partition key and sort key, if applicable). |
index (required) | Record<string, Partial<Schema>> | An object where the keys are the names of secondary indexes and the values are the key attributes for the partition key of that index.
Not required if using |
sortKeyCondition | Condition | A condition to apply to the sort key of the primary key or secondary index being queried. See Conditions for more details on building conditions. |
filter | Condition | A filter condition to apply to the results of the query. See Conditions for more details on building conditions. |
limit | number | The maximum number of total items to return in the query. |
selectAttributes | Select | Specify a subset of attributes to retrieve from the items returned by the query.
Valid values are |
reverseIndexScan | boolean | If set to true, the query will scan the index in reverse order (from highest to lowest sort key). Defaults tofalse. |
validationConcurrency | number | The number of concurrent validations to perform when validating items against the entity schema.
Internally |
exclusiveStartKey | Partial<Schema> | The primary key of the item from which to continue an earlier query.
This is used for pagination when a previous query returned a |
pageSize | number | The number of items per paginated request to DynamoDB. Only applies when using Document Builder’s pagination. |
consistent? | boolean | If set to true, DynamoDB will ensure a strongly consistent read. Defaults tofalse. |
skipValidation? | boolean |
If set to true, schema validation is bypassed entirely.
Defaults to false. |
timeoutMs? | number | Number of milliseconds to wait before the operation times out and auto-cancels. |
abortController? | AbortController | If you need to abort the commands operation, you can use the abort controller to signal cancellation. |
returnConsumedCapacity? | ReturnConsumedCapacity |
Determines the level of detail about provisioned throughput consumption that is returned in the response. Valid values are TOTAL, INDEXES, and NONE.
|
Query Command Result
Section titled “Query Command Result”The Query command returns the following result:
{ items: Schema[]; count: number; scannedCount: number; lastEvaluatedKey?: Partial<Schema>; responseMetadata?: ResponseMetadata; consumedCapacity?: ConsumedCapacity;}| Property | Type | Description |
|---|---|---|
items | Schema[] | An array of items matching the query. Will be an empty array if no items matched. |
count | number | The number of items returned in the |
scannedCount | number | The number of items that were scanned in DynamoDB to produce the results.
This may be higher than |
lastEvaluatedKey? | Partial<Schema> | If present, indicates that there are more items to retrieve for the query.
This key can be used as the |
responseMetadata? | ResponseMetadata | Metadata about the response from DynamoDB. |
consumedCapacity? | ConsumedCapacity |
Information about the capacity units consumed by the operation, if requested via the returnConsumedCapacity config.
|
Projected Query Command Config
Section titled “Projected Query Command Config”The ProjectedQuery command expects the following input config:
{ key: Partial<Schema>; index: { [indexName: string]: Partial<Schema>; }; projection: string[]; projectionSchema: ZodObject; sortKeyCondition?: Condition; filter?: Condition; limit?: number; selectAttributes?: Select; reverseIndexScan?: boolean; validationConcurrency?: number; exclusiveStartKey?: Partial<Schema>; pageSize?: number; consistent?: boolean; skipValidation?: boolean; timeoutMs?: number; abortController?: AbortController; returnConsumedCapacity?: ReturnConsumedCapacity;}Either key or index is required, but not both.
| Property | Type | Description |
|---|---|---|
key (required) | Partial<Schema> | The primary key of the item to retrieve. If using computed primary keys, only include the attributes used by your key builder functions. Otherwise this should be the attributes that make up the full primary key (partition key and sort key, if applicable). |
index (required) | Record<string, Partial<Schema>> | An object where the keys are the names of secondary indexes and the values are the key attributes for the partition key of that index.
Not required if using |
projection (required) | string[] | An array of attribute names to include in the returned items. |
projectionSchema (required) | ZodObject | A Zod schema defining the shape of the projected items. |
sortKeyCondition | Condition | An optional condition to apply to the sort key of the primary key or secondary index being queried. See Conditions for more details on building conditions. |
filter | Condition | An optional filter condition to apply to the results of the query. See Conditions for more details on building conditions. |
limit | number | The maximum number of total items to return in the query. |
selectAttributes | Select | Specify a subset of attributes to retrieve from the items returned by the query.
Valid values are |
reverseIndexScan | boolean | If set to true, the query will scan the index in reverse order (from highest to lowest sort key). Defaults tofalse. |
validationConcurrency | number | The number of concurrent validations to perform when validating items against the entity schema.
Internally |
exclusiveStartKey | Partial<Schema> | The primary key of the item from which to continue an earlier query.
This is used for pagination when a previous query returned a |
pageSize | number | The number of items per paginated request to DynamoDB. Only applies when using Document Builder’s pagination. |
consistent? | boolean | If set to true, DynamoDB will ensure a strongly consistent read. Defaults tofalse. |
skipValidation? | boolean |
If set to true, schema validation is bypassed entirely.
Defaults to false. |
timeoutMs? | number | Number of milliseconds to wait before the operation times out and auto-cancels. |
abortController? | AbortController | If you need to abort the commands operation, you can use the abort controller to signal cancellation. |
returnConsumedCapacity? | ReturnConsumedCapacity |
Determines the level of detail about provisioned throughput consumption that is returned in the response. Valid values are TOTAL, INDEXES, and NONE.
|
Projected Query Command Result
Section titled “Projected Query Command Result”The ProjectedQuery command returns the following result:
{ items: ProjectionSchema[]; count: number; scannedCount: number; lastEvaluatedKey?: Partial<Schema>; responseMetadata?: ResponseMetadata; consumedCapacity?: ConsumedCapacity;}| Property | Type | Description |
|---|---|---|
items | ProjectionSchema[] | An array of items matching the query.
Will be an empty array if no items matched.
Unlike the standard |
count | number | The number of items returned in the |
scannedCount | number | The number of items that were scanned in DynamoDB to produce the results.
This may be higher than |
lastEvaluatedKey? | Partial<Schema> | If present, indicates that there are more items to retrieve for the query.
This key can be used as the |
responseMetadata? | ResponseMetadata | Metadata about the response from DynamoDB. |
consumedCapacity? | ConsumedCapacity |
Information about the capacity units consumed by the operation, if requested via the returnConsumedCapacity config.
|
Tree-shakable Imports
Section titled “Tree-shakable Imports”import { Query } from 'dynamo-document-builder/commands/query';import { ProjectedQuery } from 'dynamo-document-builder/commands/projected-query';