Help us understand the problem. What is going on with this article?

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

概要

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

リンク

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした