Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

     

Creating DynamoDB Table using Boto3

Amazon DynamoDB is a fully managed NoSQL database service offered by Amazon Web Services (AWS). It is a fast, flexible, and scalable database service that allows users to store and retrieve data in a highly available and durable manner.

Boto3 is a Python library that provides an easy-to-use interface for interacting with various AWS services, allowing developers to automate tasks and integrate AWS services into their Python applications.

Now we going to setup step by step.

Image description

Step 1 - Go to the AWS management console and create a Cloud9 environment and create one empty folder. You can also use this GitHub repo to clone files.

GitRepo

Step 2 - Create a new file calledBooksTableCreate.py and paste this content to create DynamoDB Table. After that Run thepython BooksTableCreate.py command to run this file.

BooksTableCreate.py

import boto3dynamodb = boto3.resource('dynamodb', region_name='us-east-2')table = dynamodb.create_table(    TableName='Books',    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    })print("Table status:", table.table_status)
Enter fullscreen modeExit fullscreen mode

Create Table

After that go to the AWS console and search DynamoDB. After that in DynamoDB Dashboard you can see your DyanmoDB tables are created.
Table Create Success

Step 3 - Create a file calledbookdata.json and paste the following content.

bookdata.json

[    {        "year": 2023,        "title": "DevSecOps",        "info": {            "release_date": "2023-01-03",            "rank": 2,            "authors": [                "Daniel Bruhl",                "Chris Hemsworth",                "Olivia Wilde"            ]        }    },    {        "year": 2022,        "title": "IaaS Tools",        "info": {            "release_date": "2022-12-01",            "rank": 3,            "authors": [                "Daniel Bruhl",                "Chris Hemsworth",                "Olivia Wilde"            ]        }    }]
Enter fullscreen modeExit fullscreen mode

After that create theBooksLoadData.py file and paste the following content. Finally, run thepython BooksLoadData.py command for execution.

BooksLoadData.py

import boto3import jsonimport decimaldynamodb = boto3.resource('dynamodb', region_name='us-east-2')table = dynamodb.Table('Books')with open("bookdata.json") as json_file:    books = json.load(json_file, parse_float = decimal.Decimal)    for book in books:        year = int(book['year'])        title = book['title']        info = book['info']        print("Add Book:", year, title)        table.put_item(           Item={               'year': year,               'title': title,               'info': info,            }        )
Enter fullscreen modeExit fullscreen mode

Load data

Finally, go to the AWS management console and in the DynamoDB dashboard you can see your table added the following values.

DynamoDb Dashboard

Step 4 - Next, add new content to the table. Create anAddNewBook.py file and add the following content. After that run thepython AddNewBook.py command.

AddNewBook.py

import boto3import jsonimport decimalclass DecimalEncoder(json.JSONEncoder):    def default(self, o):        if isinstance(o, decimal.Decimal):            if abs(o) % 1 > 0:                return float(o)            else:                return int(o)        return super(DecimalEncoder, self).default(o)dynamodb = boto3.resource('dynamodb', region_name='us-east-2')table = dynamodb.Table('Books')title = "Docker"year = 2019response = table.put_item(   Item={        'year': year,        'title': title,        'info': {            "release_date": "2029-12-01",            "rank": 5,            "authors": "Daniel Bruhl"        }    })print("Add New Book:")print(json.dumps(response, indent=4, cls=DecimalEncoder))
Enter fullscreen modeExit fullscreen mode

Add New Values

Next, go to the AWS management console and in the DynamoDB dashboard you can see your latest added value in your dashboard.

AWS DynamoDB Dashboard

Step 5 - Next, get values from tables. Next, create aReadBook.py file and add the following values. Run thepython ReadBook.py command.

ReadBook.py

import boto3import jsonimport decimalfrom boto3.dynamodb.conditions import Key, Attrfrom botocore.exceptions import ClientErrorclass DecimalEncoder(json.JSONEncoder):    def default(self, o):        if isinstance(o, decimal.Decimal):            if o % 1 > 0:                return float(o)            else:                return int(o)        return super(DecimalEncoder, self).default(o)dynamodb = boto3.resource("dynamodb", region_name='us-east-2')table = dynamodb.Table('Books')title = "DevSecOps"year = 2023try:    response = table.get_item(        Key={            'year': year,            'title': title        }    )except ClientError as e:    print(e.response['Error']['Message'])else:    item = response['Item']    print("GetBook")    print(json.dumps(item, indent=4, cls=DecimalEncoder))
Enter fullscreen modeExit fullscreen mode

Get values

Step 6 - Next, query the values. CreateBooksQuery.py and add the following values. Run thepython BooksQuery.py command.

BooksQuery.py

import boto3import jsonimport decimalfrom boto3.dynamodb.conditions import Key, Attrclass DecimalEncoder(json.JSONEncoder):    def default(self, o):        if isinstance(o, decimal.Decimal):            if o % 1 > 0:                return float(o)            else:                return int(o)        return super(DecimalEncoder, self).default(o)dynamodb = boto3.resource('dynamodb', region_name='us-east-2')table = dynamodb.Table('Books')print("Books From 2023")response = table.query(    KeyConditionExpression=Key('year').eq(2023))for i in response['Items']:    print(i['year'], ":", i['title'])
Enter fullscreen modeExit fullscreen mode

Run Query

Step 7 - Finally, delete the DyanamoDB table. Because it helps to save our costs. As well as delete Cloud9 Environment. Create DeleteTable.py and add the following values. Next, run the python DeleteTable.py command.

DeleteTable.py

import boto3dynamodb = boto3.resource('dynamodb', region_name='us-east-2')table = dynamodb.Table('Books')table.delete()
Enter fullscreen modeExit fullscreen mode

Delete DynamoDB Tables

Thanks for reading the Article.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Build On!

Would you like to become an AWS Community Builder? Learn more about the program and apply to join when applications are open next.

More fromAWS Community Builders

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp