LoginSignup
16
4

More than 3 years have passed since last update.

え、CloudFormationでdynamoDBを作成するときは全カラムをプライマリー・ソートキーにしなきゃいけないんですか!?

Posted at

結論

そんなことはないです。

背景

こんな感じのテーブルを作ろうとしました。

  • 主キー:UserId(型:String)
  • カラム :Name(型:String)

なので、以下のようなテンプレートを用意しました。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: 'sam-dynamo

  Sample SAM Template for sam-dynamo

  '
Globals:
  Function:
    Timeout: 3
Resources:
  UserTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
      - AttributeName: UserId
        AttributeType: S
      - AttributeName: Name
        AttributeType: S
      KeySchema:
      - AttributeName: UserId
        KeyType: HASH
      TableName: User
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      StreamSpecification:
        StreamViewType: NEW_IMAGE

このテンプレートを実行したところ、以下のようなエラーがでました。

One or more parameter values were invalid: Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions

なんで?

先程のエラーは、「KeySchemaattributesの数と、AttributeDefinitionsattributesの数が違うぞ」という内容です。
確かに公式ドキュメントにはこのように書かれています。

Specifies the attributes that make up the primary key for the table. The attributes in the KeySchema property must also be defined in the AttributeDefinitions property.

KeySchemaにあるやつはAttributeDefinitionsにもある必要があるぞ」とのことです。
ただ、そうなると、「じゃあ最初からキーとして利用しないカラムにも属性(この場合ソートキー)を付ける必要がある?」という思考になり、大分困惑しました。

DynamoDB is schemaless (except the key schema)

そこで調べたところ、以下のような記述がありました1

DynamoDB is schemaless (except the key schema)

That is to say, you do need to specify the key schema (attribute name and type) when you create the table. Well, you don't need to specify any non-key attributes. You can put an item with any attribute later (must include the keys of course).

そういえば、DynamoDBは必要なカラムはあとから追加できましたね…
つまり、「テーブル作成時はキーとして利用するカラムのみを作成し、それ以外はあとから追加する」のが正しい利用方法ということですね。

終わりに

ちゃんと理解してる人からすれば何を当然、というようなことでしょうが、これまでMySQLしか触ってなかった自分にとって、「テーブル作成時は必要なカラムをすべて作成すべき」という認識だったので、大分ハマりました。

同様の問題に直面した方、今一度そのカラムはキーとして利用するか考えたほうが良さそうです。

参考

16
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
4