0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python初心者がboto3を使ってDynamoDBを操作するときのメモ

Last updated at Posted at 2019-09-27

はじめに

環境

$ aws --version
aws-cli/1.16.155 Python/2.7.16 Darwin/19.0.0 botocore/1.12.145

Python3のprint()をPython2系で使えるようにする

from __future__ import print_function # Python 2/3 compatibility

Python2系からPython3へ変えたとき、一番目立つ変更はprint文の記載。
2系まではprint xとスペースで空けて記述するが、
3系からはprint(x)と括弧で使って記述する。

もし、2系で3系のように括弧を使ったprint文を実行させたい場合は、
ファイルの先頭に、この文を追加する。

python - Why does using from __future__ import print_function breaks Python2-style print? - Stack Overflow

テーブルを作成する

# 
# DynamoDBへのアクセスクラスを作成
dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1')
# DynamoDBローカルを構築している場合のアクセス方法
# dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1', endpoint_url="http://localhost:8000")

table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

DynamoDBからデータを取り出すときは、パーティションキー、もしくはパーティションキーとソートキーを指定する必要がある。参照

パーティションキー(Partition Key)

  • DynamoDBのデータは複数のパーティションとよばれる保管場所、に分散されて保存されます。。
  • 同じパーティションキーの項目(アイテム)の場合、並びかたは決まっていない。(そのため、後述するソートキーを指定する必要がある)
  • パーティションキーをプライマリーキーとして使うことができる (参照)

ソートキー(Sort key)

ソートする順番を決めるためのキー
上記のコードでは、titleの文字コード順に並べられる。

時刻の取り扱い

属性の型に、日付と時刻を表す型がない。
解決策として、文字列型または数値型を使って、日付・時刻型を代替する。

    AttributeDefinitions=[
        {
            'AttributeName': 'date',
            'AttributeType': 'S'
        },

ここにハマった!DynamoDB - Technology Topics by Brains

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?