tapitapi’s blog

1日1杯タピオカ!エンジニア

【AWS DynamoDB】Create tableをPythonで行う

PythonでDynamoDBのテーブルを作成する方法をご紹介します。

(テーブル削除についてはこちら

 

リファレンス

boto3.amazonaws.com

 

まず、AWS CLIを使用できるようにする

tapitapi.hatenadiary.com

 

boto3を使用できるように、pip install

pip install boto3

 

create_table.py作成

(今回は例として、「table2」というtableを作成します。カラムは「column1」「column2」「column3」, インデックスは「column1」と「column3」のインデックスを一つ作成します)

import boto3

 

if __name__ == "__main__":

 session = boto3.Session(profile_name='default')
 client = session.client('dynamodb', region_name='us-east-2など、地域名')

   result = client.create_table(
     TableName="Table2",
     AttributeDefinitions="AttributeDefinitions": [{
      "AttributeName": "column1",
      "AttributeType": "S"
     },
    {
     "AttributeName": "column2",
     "AttributeType": "S"
    },
    {
     "AttributeName": "column3",
     "AttributeType": "S"
    }
   ],
     KeySchema=[{
      "AttributeName": "column1",
      "KeyType": "HASH"
     },
    {
    "AttributeName": "column2",
    "KeyType": "RANGE"
   }
   ],
     LocalSecondaryIndexes=[{
     "IndexName": "column1-column3-index",
     "KeySchema": [{
      "AttributeName": "column1",
      "KeyType": "HASH"
     },
    {
     "AttributeName": "column3",
     "KeyType": "RANGE"
    }
   ],
   "Projection": {
     "ProjectionType": "INCLUDE",
     "NonKeyAttributes": ["date"]
    }]
     ProvisionedThroughput={
    "ReadCapacityUnits": 15,
    "WriteCapacityUnits": 15
    } 

)

 

AttributeDefinitionsでは、使用するカラム名と型を指定します。

今回はcolumn1,2,3を指定しました。(KeySchemaでcolumn1&2, Indexでcolumn3を使用するため。)

※どこにも使用されていないColumn(Column5など)を指定するとエラーになります

※ここで指定していないColumnをKeySchemaやIndexで使用してもエラーになります

 

GUIで作成したTableを確認すると、下記のように作成できていることがわかります。

KeySchemaのカラム(最大2つまで指定可能)のみ表示されています。

f:id:kayo445:20200721191839p:plain

 

試しにデータを入れてみると、下記のようになります

NoSQLなのでAttributeDefinitionsで指定したカラム名以外のカラム(column7)も入れることができます。KeySchemaのカラム(column1&2)は必須項目になります

f:id:kayo445:20200721192008p:plain

 

Index は下記のようになります

KeySchema(column1&2)に加え、LocalSecondaryIndexesのKeySchema(column3) も表示されています。これてcolumn3の検索が速くなります

f:id:kayo445:20200721192156p:plain

以上ですー!!

 

下記レポジトリでテーブルを削除できるツール(dynamoDB/create_dynamodb_tables_json.py)を作成しましたので、使ってみてください^^

github.com

 

今後もDynamoDBに限らず、 LambdaやAPI Gatewayなど他のAWSサービス用ツールも作成していく予定です。

プルリクなどもいただけると嬉しいです!

 

おやすみなさい。