In this step, we will add a DynamoDB table resource to the SAM template and deploy it using AWS SAM CLI.
Open the template.yaml file in the fcaj-book-shop folder.
Add a new parameter booksTableName under the Parameters section:
booksTableName:
Type: String
Default: Books

Add the BooksTable resource under the Resources section:
BooksTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref booksTableName
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
- AttributeName: rv_id
AttributeType: N
- AttributeName: name
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
- AttributeName: rv_id
KeyType: RANGE
LocalSecondaryIndexes:
- IndexName: name-index
KeySchema:
- AttributeName: id
KeyType: HASH
- AttributeName: name
KeyType: RANGE
Projection:
ProjectionType: ALL

The above script creates the Books table in DynamoDB with:
id (String)rv_id (Number)name-index with sort key name (String), projecting all attributesRun the following commands to build and validate the SAM template:
sam build
sam validate

Deploy the updated stack:
sam deploy
The changeset will show a new resource BooksTable of type AWS::DynamoDB::Table being added. Enter y to confirm the deployment.

Wait for the deployment to complete. You should see Successfully created/updated stack.

Open the CloudFormation console to verify the stack status is UPDATE_COMPLETE.

Click on the fcaj-book-shop stack, switch to the Resources tab. You should see the new BooksTable resource with status CREATE_COMPLETE.

Open the DynamoDB console. At the Tables page, you should see the Books table with status Active.

Click on the Books table to view its details:
id (String), Sort key is rv_id (Number), and Capacity mode is On-demand.
Click on the Indexes tab:
name-index with Partition key id (String) and Sort key name (String).
You have now successfully created the Books table with the Local Secondary Index name-index.
ap-southeast-1).Make sure to replace all occurrences of AWS-REGION in the dynamoDB.json file with your actual AWS region before running the import command.
Run the following command at the directory where you saved the dynamoDB.json file:
aws dynamodb batch-write-item --request-items file://dynamoDB.json

If the output shows "UnprocessedItems": {}, it means all items were successfully written to the table.
To verify the data, go to the DynamoDB console, click Explore items in the left sidebar, select the Books table, and click Run to scan the table. You should see 9 items returned.
