Chào các bạn,
DynamoDB là một No-SQL database rất nổi tiếng của Amazon. Tuy nhiên vì rất nhiều lý do (trong đó lý do chính là $), bạn không thể làm việc trực tiếp với dịch vụ database của Amazon được nhưng bạn đang rất cần hiểu được cách sử dụng DynamoDB - thì đây chính là bài viết bạn cần tìm. Trong bài viết này, tôi sẽ hướng dẫn cho các bạn cách sử dụng một database DynamoDB local, sau đó dùng Python để tạo data table và nhập dữ liệu.
Bước 1: Kéo docker về với câu lệnh docker pull amazon/dynamodb-local
Bước 2: Chạy docker với câu lệnh docker run -p 8000:8000 amazon/dynamodb-local
Bước 3: Cài SDK boto3 ở đường link bên dưới.
https://pypi.org/project/boto3/
Bước 4: Viết chương trình Python để tạo table và nhập dữ liệu vào table.
import boto3 def main(): #1 - create client ddb = boto3.resource('dynamodb', endpoint_url = 'http://localhost:8000', region_name = 'dummy', aws_access_key_id='dummy', aws_secret_access_key='dummy') #2 - create table ddb.create_table(TableName="Transactions", AttributeDefinitions=[ { 'AttributeName': 'TransactionId', 'AttributeType': 'S' } ], KeySchema = [{ 'AttributeName': 'TransactionId', 'KeyType':'HASH' }], ProvisionedThroughput={ 'ReadCapacityUnits': 10, 'WriteCapacityUnits' : 10 } ) print('Successfully create Table') table = ddb.Table('Transactions') input = {'TransactionId' : '001', 'State' : 'PENDING', 'Amount' : 50} #insert data table.put_item(Item=input) print('Successfully put item') #4 - Scan table scanResponse = table.scan(TableName='Transactions') items = scanResponse['Items'] for item in items: print(item) main()
Chạy chương trình chúng ta sẽ nhận được message 'Successfully put item'.
Chúc các bạn thành công. Nếu bạn có câu hỏi, hãy để lại feedback ở mục comment bên dưới. Thank you.
About Author

I’m Viet, the founder of this website with 8+ years experience in data analytics. My sharing is focus on data, which specialise on both Analytics and Business Intelligence platform as well as Data Science and Machine Learning platform.