Python boto3 DynamoDBのscanでフィルターを指定する方法

boto3でのDynamoDBのscanでフィルターを指定の仕方が良くわからなかったので作成しました。

Pythonコード

import json
import boto3

dynamodb = boto3.client('dynamodb')

TABLENAME='テーブル名'
def dcnt(flt,val):
    nkey=''
    cnt=0
    while True:
        if nkey=='':
            response = dynamodb.scan(
                TableName=TABLENAME, 
                FilterExpression=flt,
                ExpressionAttributeValues=val,
                Select='COUNT'
                )
        else:
            response = dynamodb.scan(
                TableName=TABLENAME, 
                FilterExpression=flt,
                ExpressionAttributeValues=val,
                Select='COUNT',
                ExclusiveStartKey=nkey
                )
        cnt=cnt+response['Count']
        if 'LastEvaluatedKey' in response:
            nkey=response['LastEvaluatedKey']
        else:
            break
    
    return cnt

def main():
    tdata = dcnt(
        'begins_with(path, :t1) and flag = :t2',
        {":t1":{"S":"/START"},":t2":{"BOOL":True}},
        )
    print("%d\n" % (tdata))

if __name__ == '__main__':
    main()

フィルターをかけてその件数を出力する例です。

pathが’/START’で始まっていて、かつflagが真のものをカウントしています。

FilterExpressionに条件を書き、ExpressionAttributeValuesに検索する値を設定します。

DynamoDB scan FilterExpressionに指定できる条件式

condition-expression ::=
      operand comparator operand
    | operand BETWEEN operand AND operand
    | operand IN ( operand (',' operand (, ...) ))
    | function 
    | condition AND condition 
    | condition OR condition
    | NOT condition 
    | ( condition )

comparator ::=
    = 
    | <> 
    | < 
    | <= 
    | > 
    | >=

function ::=
    attribute_exists (path) 
    | attribute_not_exists (path) 
    | attribute_type (path, type) 
    | begins_with (path, substr) 
    | contains (path, operand)
    | size (path)