본문 바로가기

WebDev/Backend

boto dynamodb2 사용하기

boto dynamodb2 사용하기


인생은 짧고, 해야할 것은 많습니다.

pynamodb를 씁시다 (링크)



간단한 dynamodb v2사용방법!


이 글은 다음의 링크 문서를 참조해 작성했다:

튜토리얼(구버전): https://boto.readthedocs.org/en/latest/dynamodb_tut.html

튜토리얼(최신버전): https://boto.readthedocs.org/en/latest/dynamodb2_tut.html

자세한 API: http://docs.pythonboto.org/en/latest/ref/dynamodb2.html



Prerequisites



boot config 설정 http://makerj.tistory.com/191

boto config가 필요하다. dynamodb는 config에서 자동으로 key,secret,region을 읽어들이기 때문

물론 수동으로 할 수도 있지만... 사서 고생하지 말자



1. Open


from boto.dynamodb2.table import Table
t = Table('mytable')


2. CRUD



1. Create


from boto.dynamodb2.table import Table
t = Table('datepost')
t.put_item({"owner_couple_id":1,"title":"first date", "msg":"좋았다"})


2. Read


item = t.get_item(owner_couple_id=1)
for key, value in item.items():
print(key)
print(value)

추가적으로 이 item 객체를 사용해 해당 아이템의 데이터 수정도 가능하다.


쿼리 조건은 다음과 같다:

NOT_NULL     0  (exists)
NULL         0  (not exists)
EQ           1  (equal) 
NE           1  (not equal)
IN           1  (exact matches)
LE           1  (less than or equal to)
LT           1  (less than)
GE           1  (greater than or equal to)
GT           1  (greater than)
CONTAINS     1  (substring or value in a set)
NOT_CONTAINS 1  (absence of a substring or absence of a value in a set)
BEGINS_WITH  1  (a substring prefix)
BETWEEN      2  (between)
예를 들자면, title__contains="hello" tag__in=['blog','python','dynamodb'] 같이 할 수 있다는 것!




query_2를 사용한 쿼리: 키와 인덱스를 사용한 쿼리



scan을 사용한 쿼리: 검색 조건이 키와 인덱스와 관계 없을 경우




3. Update


1. Create와 같은 방법을 쓰되, 마지막에 True를 넣어줘 덮어쓰기를 해 갈아치우는 방식

from boto.dynamodb2.table import Table
t = Table('datepost')
t.put_item({"owner_couple_id":1,"title":"first date", "msg":"정말 좋았다"}, True)

2. Read로 얻은 Item을 사용해 수정하는 방식. 수정하고 save를 부르는 것을 절대 잊지 말자!

item = t.get_item(owner_couple_id=1)
item['owner_couple_id']=12345
del item['msg']
item.save()

예제처럼 del을 사용해서 속성을 제거해 버릴 수도 있다!


모든 변경이 끝났으면 꼭 저장하자!

참고로 저장은 save(overwrite=) 또는 partial_save()를 통해 가능하다. 각 함수의 의미는 명확하니 설명은 따로 필요 없고, 상황에 맞춰 적절히 사용하자


4. Delete


삭제 또한 table을 사용하는 방법, item을 사용하는 방법이 있다. 상황에 맞춰 적절히 사용하자

t.delete_item(owner_couple_id=1)

item = t.get_item(owner_couple_id=1)
item.delete()





3. Batch


한꺼번에 많은 작업을 할 때에는 batch를 하는 것이 상식이다

import time
from boto.dynamodb2.table import Table

users = Table('users')

with users.batch_write() as batch:
batch.put_item(data={
'username': 'anotherdoe',
'first_name': 'Another',
'last_name': 'Doe',
'date_joined': int(time.time()),
})
batch.put_item(data={
'username': 'joebloggs',
'first_name': 'Joe',
'last_name': 'Bloggs',
'date_joined': int(time.time()),
})
batch.delete_item(username='janedoe', last_name='Doe')

아쉬운건, 좀 짜증나는 제한이 주렁주렁 달려있다. dynamodb는 다음과 같은 한계를 갖고 있다:

  1. batch에서는 읽기 작업은 불가능하다
  2. batch안에서 batch작업을 하는 것은 불가능하다
  3. batch안에서 다룰 수 있는 아이템은 25개다! (만약 다뤄야할 아이템이 100개라면 batch를 4번 해야 한다... 이뭐..)


'WebDev > Backend' 카테고리의 다른 글

Cross Domain AJAX  (0) 2016.01.21
AWS boto accessKey, secretKey  (0) 2015.11.18
Spring boot properties  (0) 2015.11.05
Spring boot session cluster  (0) 2015.11.04
Spring Boot Package  (0) 2015.11.03