Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?
@shinsaka

DynamoDBのテーブルをscanするPythonコード

More than 1 year has passed since last update.

概要

  • boto3(AWS SDK for Python)でDynamoDBをスキャンするコードです
  • きちんとscanするために LastEvaluatedKey を使ってループする必要があります
  • 自分用スニペットです

コード

def get_records(table, **kwargs):
    while True:
        response = table.scan(**kwargs)
        for item in response['Items']:
            yield item
        if 'LastEvaluatedKey' not in response:
            break
        kwargs.update(ExclusiveStartKey=response['LastEvaluatedKey'])

使い方サンプル

フルスキャン

import boto3

dynamodb = boto3.resource('dynamodb')
records = get_records(
    dynamodb.Table('mytable')
)
for record in records:
    print(record)

フルスキャン,Projection指定

import boto3

dynamodb = boto3.resource('dynamodb')
records = get_records(
    dynamodb.Table('mytable'),
    ProjectionExpression='MyPartitionKey, MyTimestamp'
)
for record in records:
    print(record)

Projection指定,Filter指定

import boto3
from boto3.dynamodb.conditions import Key

dynamodb = boto3.resource('dynamodb')
records = get_records(
    dynamodb.Table('mytable'),
    ProjectionExpression='MyPartitionKey, MyTimestamp',
    FilterExpression=Key('MyTimestamp').begins_with('2020-02-23')
)
for record in records:
    print(record)

Projection指定,Filter指定,Index指定

import boto3
from boto3.dynamodb.conditions import Key

dynamodb = boto3.resource('dynamodb')
records = get_records(
    dynamodb.Table('mytable'),
    ProjectionExpression='MyPartitionKey, MyTimestamp',
    FilterExpression=Key('MyTimestamp').begins_with('2020-02-23'),
    IndexName='MyTimestamp-index'
)
for record in records:
    print(record)

リンク

10
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
shinsaka
IT野武士 https://github.com/shinsaka

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
10
Help us understand the problem. What is going on with this article?