LoginSignup
1
2

More than 1 year has passed since last update.

DynamoDB操作

Last updated at Posted at 2021-05-05

テーブルの作成

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
table = dynamodb.create_table(

                TableName="テーブル名",
                KeySchema=[
                    {
                        'AttributeName': 'id',
                        'KeyType': 'HASH'
                    },
                ],
                AttributeDefinitions=[
                    {
                        'AttributeName': 'id',
                        'AttributeType': 'N'
                    },
                ],
                ProvisionedThroughput={
                    'ReadCapacityUnits': 1,
                    'WriteCapacityUnits': 1
                },
            )

項目追加

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table("テーブル名")

                    table.put_item(
                        Item = {
                            'id': 1,
                            'name':"鈴木",
                            'people':"empty",
                        }
                    )

 項目の更新

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table("テーブル名")

                    table.update_item(

                        # primary_keyのみでOK
                        Key = {
                            'id': 1
                        },
                        # set 属性名 = :任意
                        UpdateExpression="set name = :name",
                        # ':任意': '変更したい文字列'
                        ExpressionAttributeValues={
                            ':name': '田中'
                        },

                    )

 項目の取り出し

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table("テーブル名")

def lambda_handler(event, context):

       queryData = table.query(
            KeyConditionExpression = Key("user_id").eq("1"),
            Limit = 1
       )

       return queryData["Items"][0]["name"]

参考文献

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