AWS DynamoDB in Python (Boto3)

ewillwin·2022년 6월 18일
0

TSMtech Record

목록 보기
1/39

DynamoDB -> Amazon에서 AWS에 최적화된 NoSQL 데이터베이스

RDBMS가 아닌 NoSQL 데이터베이스이기 때문에 별도의 SQL Programming을 하지 않고, 일반 프로그래밍 언어 상에서 DB Scheme을 설계하고 관리해야함
-> 지원 언어: Java, Javascript, Node.js, .NET, PHP, Python, Ruby

DynamoDB는 AWS의 EC2 Server 구축만 되어있고, Python, Boto3, AWS CLI 설치가 완료되면 곧바로 사용이 가능함

Table 생성

import boto3

# Get the service resource
dynamodb = boto3.resource('dynamodb')

# Create the dynamoDB table
table = dynamodb.create_table(

	Tablename = 'map_filter'
    KeySchema = [
    	{
        	'AttributeName': 'idx',
            'KeyType': 'HASH',
     	}
    ],
    AttributeDefinitions = [
    	{
        	'AttributeName': 'idx',
            'AttributeType': 'S'
        }
    ],
    ProvisionedThroughput = {
    	'ReadCapacityUnits': 5,
        'WriteCapacityUnits': 5
    }
    
)

# Wait until the table exists
table.meta.client.get_waiter('table_exists').wait(TableName = 'map_filter')

# Print out some data about the table
print(table.item_count)

-> DynamoDB의 기본 키 생성을 위해 Key schema 속성 사용
-> 기본 키에 해당하는 속성의 유형을 AttributeDefinitions로 지정하고, 문자열 유형 ('S')로 지정
-> 읽기/쓰기 용량도 지정
-> print 결과는 생성된 이후 항목(item)의 개수

Table 사용

import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("map_filter")

-> dynamodb.Table(테이블명)

Table 삭제

table.delete()

항목(item)이란 데이터 값. RDBMS에서는 Record 또는 Row라고도 하는데, DynamoDB는 NoSQL의 특성에 맞게 항목(item)으로 나타냄

기본 데이터 처리 -> CRUD(Create, Read, Update, Delete)

import boto3
import json
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError

def put_data(sd, sgg, emd, etype, btype, rtype):
    dynamodb = boto3.resource("dynamodb", region_name = "ap-northeast-2")
    table = dynamodb.Table("map_filter")
    cnt = table.scan()["Count"] + 1
    
    try:
        response = dynamodb.Table("map_filter").put_item(
            Item = {
                'idx': cnt,
                'sd': sd,
                'sgg': sgg,
                'emd': emd,
                'etype': etype,
                'btype': btype,
                'rtype': rtype,
            }
        )
    except ClientError as e:
        print(e.response["Error"]["Message"])
    else:
        return response
        
def delete_data(idx):
    dynamodb = boto3.resource("dynamodb", region_name = "ap-northeast-2")
    table = dynamodb.Table("map_filter")
    
    try:
        response = dynamodb.Table("map_filter").delete_item(
            Key = {
                'idx': idx
            }
        )
    except ClientError as e:
        print(e.response["Error"]["Message"])
    else:
        return response

def lambda_handler(event, context):
    #lambda_put_response = put_data('충청북도', '청주시', '비하동', '가스', '주거용', '전체')
    lambda_delete_response = delete_data(0)

-> 일단 map_filter는 create랑 delete까지만 구현함
-> cnt variable을 이용해서 idx (primary key) 업데이트

profile
Software Engineer @ LG Electronics

0개의 댓글