11
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-02-23

概要

  • 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)

リンク

11
16
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
11
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?