** Minimize the number of lines and characters as much as possible **, and cover (want to) how to operate DynamoDB from Python
I will write from what I actually tried (\ * ˙︶˙ \ *) و Good!
Preparations common to all operations
import boto3
from boto3.dynamodb.conditions import Attr, Key
# region_For name, write the name of your region
dynamodb = boto3.resource('dynamodb', region_name='us-east-2')
Create table
table_name = 'hoge_table'
table = dynamodb.create_table(
TableName = table_name,
KeySchema = [
{'AttributeName': 'primary_key_name', 'KeyType': 'HASH'},
{'AttributeName': 'column_name', 'KeyType': 'RANGE'}
],
AttributeDefinitions = [
{'AttributeName': 'primary_key_name', 'AttributeType': 'N'},
{'AttributeName': 'column_name', 'AttributeType': 'S'}
],
ProvisionedThroughput = {
'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1
}
)
table.meta.client.get_waiter('table_exists').wait(TableName=table_name)
AttributeName
'primary_key_name' and'column_name' are just sample names> _ <;
--'KeyType':'HASH'
will be the partition key
--'KeyType':'RANGE'
is the sort key'AttributeType':'S'
makes it a string type column
--'AttributeType':'N'
makes it a numeric columnGet table list
# region_For name, write the name of your region
client = boto3.client('dynamodb', region_name='us-east-2')
client.list_tables()['TableNames']
Get 1 record
table_name = 'hoge_table'
table = dynamodb.Table(table_name)
table.get_item(
Key={'primary_key_name': 1, 'column_name': 'string_value'}
).get('Item')
After getting all items, filter by Attribute It is said that it consumes extra resources compared to query () (AWS usage fee is extra)
Filtering after getting all
table_name = 'hoge_table'
table = dynamodb.Table(table_name)
table.scan(
FilterExpression=Attr('column_name').eq('string_value'),
Limit=1 #You can specify the number of cases. There is no need to have one separately.
).get('Items')
Get only records that meet the conditions
filtered search
table_name = 'hoge_table'
table = dynamodb.Table(table_name)
#Column name is appropriate
table.query(
KeyConditionExpression=Key('column_name1').eq('string_value') & Key('column_name2').between(from_str, to_str)
)
(I want to start a new line at some point, but I'm angry with the Lint tool ...)
table_name = 'hoge_table'
table = dynamodb.Table(table_name)
items_source = [
{'primary_key_name': 1, 'column_name': 'hoge1'},
{'primary_key_name': 2, 'column_name': 'hoge2'},
...(Abbreviation)
{'primary_key_name': 9, 'column_name': 'hoge9'}
]
# `overwrite_by_pkeys`For the column specified in, if it is duplicated, the record will be overwritten.
#If this is not specified, an error will be thrown when the value is duplicated.
with table.batch_writer(overwrite_by_pkeys=['primary_key_name', 'column_name']) as batch:
for item in items_source:
batch.put_item(Item=item)
-I tried to operate DynamoDB with Boto3 -Create table and register data in DynamoDB Local with Python (boto3)
Recommended Posts