Skip to content

Commit 9c6a29e

Browse files
authored
docs(lib-dynamodb): example for performing table scan (#7227)
1 parent 512c493 commit 9c6a29e

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

lib/lib-dynamodb/README.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,77 @@ await impreciseClient.send(
303303
);
304304
```
305305

306+
### Example: performing a full table scan
307+
308+
Before performing a full table scan, consider whether your query can be satisfied by a more efficient operation.
309+
For instance, if you are searching for a set of rows by primary keys, `BatchGetItem` may be better.
310+
311+
First, initialize the base Client and Document Client.
312+
313+
```ts
314+
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
315+
import { DynamoDBDocumentClient, paginateScan, ScanCommand } from "@aws-sdk/lib-dynamodb";
316+
317+
const client = new DynamoDBClient({
318+
region: "us-west-2",
319+
});
320+
321+
const docClient = DynamoDBDocumentClient.from(client);
322+
323+
const paginatorConfiguration = {
324+
client: docClient,
325+
};
326+
327+
/**
328+
* This is a function so as to create
329+
* separate objects per request.
330+
*
331+
* The objects passed into AWS SDK Command instances
332+
* are retained as references, so this prevents unexpected mutations.
333+
*/
334+
const scanRequestInput = () => ({
335+
TableName: "YOUR_TABLE_NAME",
336+
Limit: 100,
337+
});
338+
```
339+
340+
The recommended way to iterate the scan is with our library's paginator helper function.
341+
342+
```ts
343+
// Recommended method, using the AWS SDK paginator:
344+
let pageNumber = 1;
345+
for await (const page of paginateScan(paginatorConfiguration, scanRequestInput())) {
346+
console.log("page:", pageNumber++);
347+
console.log(page.Items);
348+
}
349+
```
350+
351+
Alternatively, the equivalent manual method, which is exactly what the paginator function
352+
is doing internally, is with a loop utilizing the pagination token from the responses:
353+
354+
```ts
355+
// Manual method, using the ScanCommand and pagination token:
356+
let pageNumber = 1;
357+
const firstPage = await docClient.send(new ScanCommand(scanRequestInput()));
358+
console.log("page:", pageNumber++);
359+
console.log(firstPage.Items);
360+
361+
let paginationToken = firstPage.LastEvaluatedKey;
362+
363+
while (paginationToken) {
364+
const page = await docClient.send(
365+
new ScanCommand({
366+
...scanRequestInput(),
367+
ExclusiveStartKey: paginationToken,
368+
})
369+
);
370+
paginationToken = page.LastEvaluatedKey;
371+
372+
console.log("page:", pageNumber++);
373+
console.log(page.Items);
374+
}
375+
```
376+
306377
### Client and Command middleware stacks
307378

308379
As with other AWS SDK for JavaScript v3 clients, you can apply middleware functions

0 commit comments

Comments
 (0)