使用 AWS SDK v2 在 Ruby 中创建表

在下面的示例中,我们将使用 AWS Ruby SDK v2 创建表 movies。在这里,每个 Movie 都作为一个独特的分区键,如 id 和 Range Key year。除此之外,我们希望能够用他们的名字查询电影,因此我们将创建一个全局二级索引(GSI)name-year-index,其中 name 为 Hash Key,year 为 Range Key。电影可以有其他属性,如 releasedcreated_atactoractress。该表的模式如下所示:

表名 :电影

分区键 范围键 全局二级指数 属性
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"})