Create a table in DynamoDB

In this section of the tutorial, we will learn how to create a table in DynamoDB.

To create a table in any database you first need to create a database server itself. In the case of DynamoDB that is not necessary. Since it is fully managed by AWS the server configuration is not needed. You can directly begin by creating a table in the AWS console.

We can create a DynamoDB using one of the following four ways:

  1. AWS console – in the browser and use the user interface to create a table
  2. AWS CLI – AWS provides CLI to perform table creation
  3. AWS SDK – AWS SDK for AWS supported programming languages
  4. AWS CloudFormation – IaC

AWS console to create a table in DynamoDB

This is the simplest way to create a table in DynamoDB. For this, follow the following steps:

  1. Log in to AWS console
  2. Go to services > DynamoDB
  3. There you will see an option Create Table. Click the option.
  4. Enter the table name and a primary key name.
Create a table in DynamoDB
create a table in DynamoDB

This will create a DynamoDB table with the table name you specified and the primary key specified. Let us look more into the partition key.

Primary Key

Like any other database, you need to specify a unique attribute in a table. The partition key is a unique identifier of any item you store in the table. DynamoDB data can be retrieved using the primary key. A partition key can be one of

  1. Partition Key
  2. Partition key + Sort Key

Partition Key

DynamodDB is scalable because by default it stores the items of a table in various partitions. The partition is based on the partition key we specify.

DynamoDB partition
DynamoDB partition

DynamoDB automatically stores and retrieves data based on the primary key. It determines the partition in which it needs to store/retrieve items based on the internal hash function.

Sort Key

When we specify a sort key, the data is inside a partition is sorted based on the key. This helps query faster within a partition. If the data size within a partition gets bigger than 10GB it is split based on the sort key.

How to choose the right partition key?

  • Use the key that you want to access the data mostly with. For example in a books table, use book_id as a primary key and not a random ID that you do not query the table with.
  • Use a unique key for the partition key
  • Make sure your access pattern is equally distributed across different partitions. If most of your transaction is always reading one partition on a table that will cause all the load to be handled by a single partition.
  • If your application is write-heavy add a prefix to your partition key. With this, you can ensure that the item write is being equally distributed across different partitions and not only a single partition is handling a big write.

AWS CLI to create a table

AWS is always CLI first. This means that any features developed by AWS are available via the AWS CLI

If you have not installed you can install the AWS CLI in your machine you can follow this guide

Once the CLI is installed we can now create a table.

aws dynamodb create-table \
     --table-name Book \
     --attribute-definitions \
         AttributeName=Author,AttributeType=S \
         AttributeName=Category,AttributeType=S \
     --key-schema AttributeName=Author,KeyType=HASH AttributeName=Category,KeyType=RANGE \
     --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5

To perform any action via CLI for DynamoDB we use the command aws dynamodb. Here we are creating a table so the command is aws dynamodb create-table

In the above CLI command, we can see 4 main parameters provided to the AWS CLI for create-table command.

–table-name The name of the table we want to create. In this case a book table

–attribute-definitions The attributes that we need to predefine to AWS which will include partition key and sort key as needed. In this case, we need the Author and Category of the book. Both of them are strings so we are representing it as S. A single attribute is defined in the format AttributeName=Author,AttributeType=S

–key-schema In this argument we define which is our partition key and which is our sort key. Here we will be using Author as the partition key and category and the sort key. We define the key schema in the following format

AttributeName=Author,KeyType=HASH

Here the AttributeName is the name of the attribute we defined in the attribute-definitions section. The keyType can be either a HASH or a RANGE. If it is a HASH we are telling DynamoDB that it is the partition key. The section key-schema after that has a RANGE value in the keyType, which is the sort KEY.

–provisioned-throughput Here we define how much throughput we want to provision for the DynamoDB read/write

When there are a large number of attribute definitions needed it will be messy to define all of them in a single CLI command. So we have an option to provide a file for the arguments for the create table in DynamoDB.

Using a file to organize the CLI arguments

aws dynamodb create-table --cli-input-json file://booktable.json

We need to define a file called booktable.json where we can provide the necessary argument:

{
         "AttributeDefinitions": [
             {
                 "AttributeName": "Author",
                 "AttributeType": "S"
             },
             {
                 "AttributeName": "Category",
                 "AttributeType": "S"
             }
         ],
         "TableName": "books",
         "KeySchema": [
             {
                 "AttributeName": "Author",
                 "KeyType": "HASH"
             },
             {
                 "AttributeName": "Category",
                 "KeyType": "RANGE"
             }
         ],
         "ProvisionedThroughput": {
             
"ReadCapacityUnits": 5,
             "WriteCapacityUnits": 5
         }
 }

With this file and the command to create a table becomes more organized.

Using AWS SDK to create a table

You can use any AWS SDK to create a DynamoDB table. In this tutorial we will be using Golang to create a table:

// createDynamoDB.go

 package main

 import (
     "fmt"
     "github.com/aws/aws-sdk-go/service/dynamodb"
 )

 func main() {
     // AWS session
     mySession := session.Must(session.NewSession())

     // A DynamoDB client
     svc := dynamodb.New(mySession)

     // Create a table
     attr := dynamodb.AttributeDefinition{
     AttributeName: "Author",
     "AttributeType": "S"
  }
     attributeDefinitions := []dynamodb.AttributeDefinition{attr}
     schema := dynamodb.KeySchemaElement{
       AttributeName: "Author", 
      "KeyType": "HASH"
    }
     keySchema := []dynamodb.KeySchemaElement{&schema}
     input := dynamodb.CreateTableInput{
      AttributeDefinitions: &attributeDefinitions,
      KeySchema: &keySchema} 
     out, err := svc.CreateTable(&input)
     if err != nil { 
        fmt.Println(err)
     }
     fmt.Println(out)
 }

We can also create a Table using AWS Cloudformation. We will learn about it in the coming sections.

You can use any one of the above mechanisms to create DynamoDB table. In the next section of the tutorial, we will learn to insert data in the table we just created.

Leave a Reply