LoginSignup
9
9

More than 5 years have passed since last update.

Python botoからDynamoの操作の事始め

Last updated at Posted at 2015-08-19

初めに

Boto(AWSのPython SDK)を使ってDynamo DBにアクセスしたい、と思ったのですが、初歩的な部分でずばり参考になるSample Codeがうまく見つからなかったので、作成したCodeをチラシの裏しておきます。

Dynamoにアクセスしてget_item, query_2, scanをするCode

以下を前提にしています
  • Dynamoへのアクセス権が付与されたIAM Userは作成済で、Access Key IDSecret Access Keyも作成済
  • DynamoにはrequestsというTableが既にある
  • requests tableのHashkeyがStringでuserID、Range KeyがNumberでcreated_date
#!/usr/bin/env python
# coding: utf-8

import boto.dynamodb2
from boto.dynamodb2.table import Table

#AWS Keys for Dynamo
aws_access_key_id = 'AKIASJOE73SDGDTDA'
aws_secret_access_key = 'BuAHZv01Us0pZTbe87987JOIeuoeaM3MO'
aws_region = 'ap-northeast-1'

def main():
  conn = boto.dynamodb2.connect_to_region(aws_region, aws_access_key_id=aws_access_key_id,
                       aws_secret_access_key=aws_secret_access_key)

  requests = Table('requests', connection=conn)

  # show # of items
  print requests.count()


  # 'get_key_fields' example to show hash/range-key info for this table
  print requests.get_key_fields()


  # 'get_item' example to show all attribute of a item which has particular userID/created_date
  item = requests.get_item(userID='USER-ID-0123-EDSMQNAK', created_date=143918255309)
  for field, val in item.items():
    print "%s: %s" % (field, val)


  # 'query_2' example to query items with particular userID, and show all attributes for each item
  # need to set 'userID__eq', not 'userID' 
  query_item = requests.query_2(userID__eq='USER-ID-0123-EDSMQNAK')
  for item in query_item:
    for field, val in item.items():
      print '%s: %s' % (field, val)
    print '--------------------'


  # 'query_2' example to query items of userID (_eq) AND range key (__gt) 
  query_item = requests.query_2(userID__eq='USER-ID-0123-EDSMQNAK', created_date__gt=143918200000)


  # 'scan' example to scan with key "last_access_day" >= "20150810" 
  query_item = requests.scan(last_access_day__gte=20150810)

if __name__ == '__main__':
  main()

補足

get_item, query_2, scanの違い
  • get_itemは、Key (hash or hash+range_key)を指定して、Best matchするitemを1件取り出す
  • query_2は、Key (hash or hash+range_key)を検索条件として、Matchするitemを複数取り出す。検索条件としてKeyしか使えない。range_keyに対しては、KeyConditionExpressionという演算子(EQ|LE|LT|GE|GT|BEGINS_WITH|BETWEEN)でgreather, lessなどの範囲指定が可能
  • scanは、いわゆる全文検索で、Key以外のattributeを検索条件に検索が可能です (が、read capacity unitを大量消費します)
  • Amazonの公式Documentはこちらを参照
9
9
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
9
9