LoginSignup
15
8

More than 1 year has passed since last update.

DynamoDBのデータ型とPythonのデータ型の対応

Last updated at Posted at 2021-06-05

DynamoDBのデータ型は以下があります。Pythonのboto3でDynamoDBからデータを取得したときに、Pythonではどういうオブジェクトになるのかを確認しました。

  • String
  • Binary
  • Number
  • Boolean
  • Null
  • List
  • Map
  • Set of String
  • Set of Binary
  • Set of Number

DynamoDBとPythonのデータ型の対応

boto3のclientを使う場合とresourceを使う場合とで、扱いが異なります。

session.client("dynamodb").get_item は値とともにデータ型の情報が付随してきます。
session.resource("dynamodb").Table(table_name).get_item は直接Pythonのオブジェクトに変換されて取得できます。

DynamoDBでの型 client resource
String {'S': 'abc'} 'abc'
Binary {'B': b'Hello,\nWorld!\n'} Binary(b'Hello,\nWorld!\n')
Number {'N': '1234'} Decimal('1234')
Boolean {'BOOL': True} True
Null {'NULL': True} None
List {'L': [{'S': 'abc'}, {'N': '123'}]} ['abc', Decimal('123')]
Map {'M': {'entry1': {'S': 'abc'}, 'entry2': {'S': 'def'}}} {'entry1': 'abc', 'entry2': 'def'}
Set of String {'SS': ['abc', 'def']} {'abc', 'def'}
Set of Binary {'BS': [b'Hello,\n', b'World!\n']} {Binary(b'World!\n'), Binary(b'Hello,\n')}
Set of Number {'NS': ['123', '456']} {Decimal('456'), Decimal('123')}

2列目は session.client("dynamodb").get_item で取得した結果です。
3列目は session.resource("dynamodb").Table(table_name).get_item で取得した結果です。

いずれもPythonの pprint での出力です。

Pythonコード

確認に使ったPythonのソースコードです。

from pprint import pformat

import boto3

profile = "default"
table_name = "sample"
record_id = "test1234"

session = boto3.session.Session(profile_name = profile)
dynamodb_client = session.client("dynamodb")

res = dynamodb_client.get_item(
    TableName = table_name,
    Key = {
        "Id": {
            "S": record_id,
        },
    },
)
for col, value in res["Item"].items():
    print(f"{col}: {pformat(value)}")

print()

dynamodb_resource = session.resource("dynamodb")
table = dynamodb_resource.Table(table_name)

res = table.get_item(
    Key = {
        "Id": record_id,
    },
)

for col, value in res["Item"].items():
    print(f"{col}: {pformat(value)}")
15
8
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
15
8