Build an Application Using a NoSQL Key-Value Data Store
GETTING STARTED GUIDE
Module 2: Inserting and retrieving data
Create a table for the bookstore application and insert and retrieve data
Introduction
In this module, you will create a table for our bookstore application using the DynamoDB CreateTable API. You will then insert and retrieve items using PartiQL. As a refresher, PartiQL is a SQL-compatible query language that enables you to work with data across different indexed stores, regardless of the level of structure. To learn more about PartiQL, see What is PartiQL? in the Amazon DynamoDB Developer Guide.
Time to Complete
15 minutes
Prerequisites
- An AWS account: if you don't already have one, follow the Setting Up Your Environment getting started guide for a quick overview.
- An installed version of the AWS SDK via pip install boto3
Implementation
Step 1: Create table
You need to create a table with the following schema to store books from the product catalog:
- Title (a string): The title of the book
- Author (a string): The author of the book
- Category (a string): The category of the book, such as history, biography, and sci-fi
- Formats (a map): The different formats that you have available for sale (such as hardcover, paperback, and audiobook) and their item numbers in your inventory system
You also want to make sure that our table has a composite primary key of Author and Title.
- The script specifies the composite primary key of your table with the KeySchema argument in the CreateTable API call.
- With DynamoDB, you can set read and write capacity separately, allowing you to fine-tune your configuration to meet your application’s needs without paying for costly over-provisioning.
import boto3
# boto3 is the AWS SDK library for Python.
# We can use the low-level client to make API calls to DynamoDB.
client = boto3.client('dynamodb', region_name='us-east-1')
try:
resp = client.create_table(
TableName=\"Books\",
# Declare your Primary Key in the KeySchema argument
KeySchema=[
{
"AttributeName": "Author",
"KeyType": "HASH"
},
{
"AttributeName": "Title",
"KeyType": "RANGE"
}
],
# Any attributes used in KeySchema or Indexes must be declared in AttributeDefinitions
AttributeDefinitions=[
{
"AttributeName": "Author",
"AttributeType": "S"
},
{
"AttributeName": "Title",
"AttributeType": "S"
}
],
# ProvisionedThroughput controls the amount of data you can read or write to DynamoDB per second.
# You can control read and write capacity independently.
ProvisionedThroughput={
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
}
)
print("Table created successfully!")except Exception as e:
print("Error creating table:")
print(e)
Step 2: Insert items into our books table
Create a file called partiqlbatch.json
[
{
"Statement": "INSERT INTO \"Books\" VALUES {'Author': 'Antje Barth', 'Title': 'Data Science on AWS','Category': 'Technology', 'Formats': { 'Hardcover': 'J4SUKVGU', 'Paperback': 'D7YF4FCX' }}"
},
{
"Statement": "INSERT INTO \"Books\" VALUES {'Author': 'Julien Simon', 'Title': 'Learn Amazon SageMaker','Category': 'Technology', 'Formats': { 'Hardcover': 'Q7QWE3U2','Paperback': 'ZVZAYY4F', 'Audiobook': 'DJ9KS9NM' }}"
},
{
"Statement": "INSERT INTO \"Books\" VALUES {'Author': 'James Patterson', 'Title': 'Along Came a Spider','Category': 'Suspense', 'Formats': { 'Hardcover': 'C9NR6RJ7','Paperback': '37JVGDZG', 'Audiobook': '6348WX3U' }}"
},
{
"Statement": "INSERT INTO \"Books\" VALUES {'Author': 'Dr. Seuss', 'Title': 'Green Eggs and Ham','Category': 'Children', 'Formats': { 'Hardcover': 'GVJZQ7JK','Paperback': 'A4TFUR98', 'Audiobook': 'XWMGHW96' }}"
},
{
"Statement": "INSERT INTO \"Books\" VALUES {'Author': 'William Shakespeare', 'Title': 'Hamlet', 'Category': 'Drama', 'Formats': { 'Hardcover': 'GVJZQ7JK','Paperback': 'A4TFUR98', 'Audiobook': 'XWMGHW96' }}"
}
]
In the command line, run the following:
aws dynamodb batch-execute-statement --statements file://partiqlbatch.json
You have now loaded five books into the table. Each book includes the Author and Title attributes for the primary key, and Category and Formats attributes for additional information about the books. Each attribute has a type, which can be a simple type such as a string for the Category attribute, or a complex type such as a map for the Formats attribute.
Step 3: Retrieve an item from our books table
This following code will retrieve a single item, which is the book Data Science on AWS by Antje Barth.
import boto3
dynamodb = boto3.client('dynamodb', region_name='us-east-1')
resp = dynamodb.execute_statement(Statement='SELECT * FROM Books WHERE Author = \'Antje Barth\' AND Title = \'Data Science on AWS\'')
print(resp['Items'])
It should return the following:
{'Author': 'Antje Barth', 'Title': 'Data Science on AWS','Category': 'Technology', 'Formats': { 'Hardcover': 'J4SUKVGU', 'Paperback': 'D7YF4FCX' }}
Conclusion
In this module you created a table for our bookstore application using the DynamoDB CreateTable API, and inserted and retrieved items using PartiQL.
Up Next: Querying and secondary indexes