使用 AWS SDK v2 在 Ruby 中建立表
在下面的示例中,我們將使用 AWS Ruby SDK v2 建立表 movies
。在這裡,每個 Movie 都作為一個獨特的分割槽鍵,如 id
和 Range Key year
。除此之外,我們希望能夠用他們的名字查詢電影,因此我們將建立一個全域性二級索引(GSI)name-year-index
,其中 name
為 Hash Key,year
為 Range Key。電影可以有其他屬性,如 released
,created_at
,actor
和 actress
。該表的模式如下所示:
表名 :電影
分割槽鍵 | 範圍鍵 | 全域性二級指數 | 屬性 |
---|---|---|---|
ID |
年 | 名稱 | 釋出,created_at,演員,女演員 |
# 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"})