Creating and Managing DynamoDB Tables using the AWS CLI
Introduction to DynamoDB
Amazon DynamoDB is a fully managed NoSQL database service designed for fast and predictable performance at any scale. It offers flexible scalability, high availability, and low latency to power internet-scale applications.
Some of the key features and benefits of DynamoDB include:
- Automatic scaling of throughput capacity to maintain consistent performance
- Seamless scalability to handle trillions of requests per day
- Sub-millisecond response times for accessing data
- High availability with multi-AZ replication and automatic failover
- Integrated caching with DynamoDB Accelerator (DAX) for microsecond latency
- Flexible data model with tables, items, and attributes
- Event-driven programming with DynamoDB Streams
- Robust security with encryption at rest and in transit
- Backup and restore capabilities for point-in-time recovery
Common use cases for DynamoDB span a variety of application needs:
- User profile stores and session data
- Real-time gaming leaderboards
- Product catalogs and shopping carts for ecommerce
- Timestamped log and metric data
- Content management and metadata stores
- Fraud detection with transactions and clickstream data
While the AWS Management Console provides a visual interface for working with DynamoDB, the AWS Command Line Interface (CLI) enables direct access to service APIs for granular control and automation. In this guide, we‘ll walk through using the AWS CLI to create and manage DynamoDB tables.
Installing and Configuring the AWS CLI
The first step is to install the AWS CLI on your local machine. The CLI is available for Linux, macOS, and Windows. Follow the appropriate instructions for your operating system:
Linux:
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
macOS:
$ curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
$ sudo installer -pkg AWSCLIV2.pkg -target /
Windows:
Download and run the AWS CLI MSI installer from https://awscli.amazonaws.com/AWSCLIV2.msi
Once installed, verify the CLI version:
$ aws --version
aws-cli/2.2.6 Python/3.8.8 Darwin/20.3.0 source/x86_64 prompt/off
Next, configure the CLI with your AWS credentials and default region:
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json
You can also set these as environment variables:
$ export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
$ export AWS_DEFAULT_REGION=us-west-2
With the AWS CLI installed and configured, you‘re ready to start working with DynamoDB.
Creating a DynamoDB Table
DynamoDB tables are created with the create-table command. At a minimum, you must specify the table name, attribute definitions, key schema, and billing mode.
The basic syntax is:
$ aws dynamodb create-table \
--table-name <table-name> \
--attribute-definitions <attributes> \
--key-schema <key-schema> \
--billing-mode <billing-mode>
For example, let‘s create an Employee table with attributes for ID, name, department, title, and salary:
$ aws dynamodb create-table \
--table-name Employees \
--attribute-definitions \
AttributeName=ID,AttributeType=S \
AttributeName=Department,AttributeType=S \
--key-schema \
AttributeName=ID,KeyType=HASH \
AttributeName=Department,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST
This specifies:
- Table name is Employees
- Two attributes in the key schema:
- ID (string) as the partition key
- Department (string) as the sort key
- On-demand billing mode (pay only for what you use)
If the command succeeds, you‘ll see output describing the table:
{
"TableDescription": {
"AttributeDefinitions": [
{
"AttributeName": "ID",
"AttributeType": "S"
},
{
"AttributeName": "Department",
"AttributeType": "S"
}
],
"TableName": "Employees",
"KeySchema": [
{
"AttributeName": "ID",
"KeyType": "HASH"
},
{
"AttributeName": "Department",
"KeyType": "RANGE"
}
],
"BillingModeSummary": {
"BillingMode": "PAY_PER_REQUEST"
},
"TableStatus": "CREATING",
...
}
}
To confirm the table exists, use the list-tables command:
$ aws dynamodb list-tables
{
"TableNames": [
"Employees"
]
}
You now have a DynamoDB table ready to store employee data. The table status will be CREATING for a short period, then transition to ACTIVE when it‘s ready for use.
Managing Tables and Items
With a table created, you can use additional CLI commands to manage the table itself and work with its data.
Describing a Table
The describe-table command provides detailed information about the table:
$ aws dynamodb describe-table --table-name Employees
{
"Table": {
"TableName": "Employees",
"TableStatus": "ACTIVE",
"TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/Employees",
"AttributeDefinitions": [
{
"AttributeName": "ID",
"AttributeType": "S"
},
{
"AttributeName": "Department",
"AttributeType": "S"
}
],
"KeySchema": [
{
"AttributeName": "ID",
"KeyType": "HASH"
},
{
"AttributeName": "Department",
"KeyType": "RANGE"
}
],
"BillingModeSummary": {
"BillingMode": "PAY_PER_REQUEST"
},
"ProvisionedThroughput": {
"ReadCapacityUnits": 0,
"WriteCapacityUnits": 0
},
...
}
}
This returns the table name, status, Amazon Resource Name (ARN), attributes, keys, billing mode, provisioned throughput, and other properties.
Adding an Item
To add an item (row) to the table, use put-item:
$ aws dynamodb put-item \
--table-name Employees \
--item \
‘{"ID": {"S": "1"}, "Department": {"S": "Engineering"}, "Name": {"S": "Jane Doe"}, "Title": {"S": "Software Engineer"}, "Salary": {"N": "150000"}}‘
The –item argument specifies the attribute names and values. Data types are denoted with type descriptors like S for string and N for number.
Getting an Item
To retrieve an item by its key, use get-item:
$ aws dynamodb get-item \
--table-name Employees \
--key ‘{"ID": {"S": "1"}, "Department": {"S": "Engineering"}}‘
{
"Item": {
"Title": {
"S": "Software Engineer"
},
"Salary": {
"N": "150000"
},
"ID": {
"S": "1"
},
"Department": {
"S": "Engineering"
},
"Name": {
"S": "Jane Doe"
}
}
}
The –key argument specifies the partition and sort key values.
Updating an Item
To modify an existing item, use update-item:
$ aws dynamodb update-item \
--table-name Employees \
--key ‘{"ID": {"S": "1"}, "Department": {"S": "Engineering"}}‘ \
--update-expression "SET Salary = :s" \
--expression-attribute-values ‘{":s": {"N": "160000"}}‘
This updates Jane‘s salary to 160000 using an update expression. Refer to the update expressions documentation for the full syntax.
Deleting an Item
To remove an item from the table, use delete-item:
$ aws dynamodb delete-item \
--table-name Employees \
--key ‘{"ID": {"S": "1"}, "Department": {"S": "Engineering"}}‘
As with get-item, the –key argument identifies the specific item to delete.
Querying Data
You can use the query command to retrieve items based on partition key equality and sort key conditions:
$ aws dynamodb query \
--table-name Employees \
--key-condition-expression "ID = :id" \
--expression-attribute-values ‘{":id": {"S": "1"}}‘
This queries the Employees table for all items with ID = 1. See the key condition expressions documentation for more complex queries.
Scanning Data
The scan operation retrieves all items in the table:
$ aws dynamodb scan --table-name Employees
{
"Items": [
{
"Title": {
"S": "Software Engineer"
},
"Salary": {
"N": "160000"
},
"ID": {
"S": "1"
},
"Department": {
"S": "Engineering"
},
"Name": {
"S": "Jane Doe"
}
}
],
"Count": 1,
"ScannedCount": 1
}
You can also specify filter expressions to refine the results. Keep in mind that a scan always scans the entire table and should be used sparingly with large tables.
Backing Up a Table
DynamoDB offers on-demand and continuous backups for disaster recovery. To create an on-demand backup, use create-backup:
$ aws dynamodb create-backup \
--table-name Employees \
--backup-name EmployeesBackup
List your backups with list-backups:
$ aws dynamodb list-backups
{
"BackupSummaries": [
{
"TableName": "Employees",
"BackupName": "EmployeesBackup",
"BackupStatus": "AVAILABLE",
"BackupType": "USER",
"BackupCreationDateTime": 1621022800.0,
"BackupSizeBytes": 1000,
...
}
]
}
To restore a table from backup, use restore-table-from-backup.
Deleting a Table
Finally, to delete a DynamoDB table, use delete-table:
$ aws dynamodb delete-table --table-name Employees
This will remove the table and all of its data. Use with caution as this operation is not reversible.
Conclusion
The AWS CLI provides a powerful set of commands for creating and managing DynamoDB tables. In this guide, we covered:
- Installing and configuring the AWS CLI
- Creating a table with create-table
- Describing table details with describe-table
- Adding, retrieving, updating, and deleting items
- Querying and scanning table data
- Creating backups for disaster recovery
- Deleting tables with delete-table
For a full reference of DynamoDB commands and options, see the CLI documentation.
While the CLI enables direct, granular control through scripts and automation, keep in mind that AWS also offers SDKs in various programming languages like Java, .NET, Node.js, PHP, Python, and more. The SDKs provide language-specific APIs for working with DynamoDB and other AWS services programmatically.
Whether you use the CLI, SDKs, or management console, DynamoDB‘s flexible billing, high performance, and scalable capacity make it a compelling choice for diverse application needs. As a fully managed service, it allows you to focus on building great apps without worrying about database operations.
I hope this guide helps you get started with DynamoDB and the AWS CLI. For more in-depth tutorials and best practices, check out the official DynamoDB documentation. Feel free to leave a comment if you have any questions!