In following example we will create table movies with AWS Ruby SDK v2.
Here, each Movie as one unique Partition Key as id, and Range Key year. Apart from this we want to be able to query movies with their name, hence we will create a Global Secondary Index (GSI) name-year-index with name as Hash Key and year as Range Key. Movie can have other attributes such as released, created_at, actor and actress. Schema for the table is shown below:
Table Name: movies
| Partition Key | Range Key | Global Secondary Index | Attributes |
|---|---|---|---|
| id | year | name | released , created_at, actor, actress |
# it's better to initialize client as global variable in initializer
$ddb ||= Aws::DynamoDB::Client.new({
access_key_id: ENV["AWS_ACCESS_KEY_ID"],
secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]
})
# create table API
$ddb.create_table({
# array of attributes name and their type that describe schema for the Table and Indexes
attribute_definitions: [
{
attribute_name: "id",
attribute_type: "N"
}
{
attribute_name: "name",
attribute_type: "S",
},
{
attribute_name: "year",
attribute_type: "N",
}
],
# key_schema specifies the attributes that make up the primary key for a table
# HASH - specifies Partition Key
# RANGE - specifies Range Key
# key_type can be either HASH or RANGE
key_schema: [
{
attribute_name: "id",
key_type: "HASH",
},
{
attribute_name: "year",
key_type: "RANGE",
}
],
# global_secondary_indexes array specifies one or more keys that makes up index, with name of index and provisioned throughput for global secondary indexes
global_secondary_indexes: [
index_name: "name-year-index",
key_schema: [
{
attribute_name: "name",
key_type: "HASH"
},
{
attribute_name: "year",
key_type: "RANGE"
}
],
# Projection - Specifies attributes that are copied (projected) from the table into the index.
# Allowed values are - ALL, INCLUDE, KEYS_ONLY
# KEYS_ONLY - only the index and primary keys are projected into the index.
# ALL - All of the table attributes are projected into the index.
# INCLUDE - Only the specified table attributes are projected into the index. The list of projected attributes are then needs to be specified in non_key_attributes array
projection: {
projection_type: "ALL"
},
# Represents the provisioned throughput settings for specified index.
provisioned_throughput: {
read_capacity_units: 1,
write_capacity_units: 1
}
],
# Represents the provisioned throughput settings for specified table.
provisioned_throughput: {
read_capacity_units: 1,
write_capacity_units: 1,
},
table_name: "movies"
})
# wait till table is created
$ddb.wait_until(:table_exists, {table_name: "movies"})