DynamoDB Local
Boto3 DynamoDB Docs
Create DynamoDB
java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar -port 7000
Boto3 API
Initiate Resource
- Use 'resource' object whenever possible
- Use 'client' object when necessary. This a lower-level API
import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:7000')
table = dynamodb.Table('table_name')
session = boto3.Session(profile_name='profile')
dynamodb = session.resource('dynamodb')
Read
Query
response = table.query(
KeyConditionExpression=Key('mall').eq('The Sono Collection')
)
for i in response['Items']:
print(i)
Scan
- Scans the whole table - inefficient but necessary for non-hash key queries
scan = table.scan()
fe = Key('sort_key').begins_with('TEST#')
response = user_table.scan(
FilterExpression=fe
)
items = []
for i in response['Items']:
if i['key'] not in items:
items.append(i['key'])
Expressions
fe = Key('sortkey').begins_with('Test#Hello') & Attr('example').exists()
- ProjectionExpression - Choose which attributes are displayed (Done after the query, different from SELECT)
ProjectionExpression='attribute1, attribute2, attribute3'
Create
Create Table
table = dynamodb.create_table(
TableName='GridEquip',
KeySchema=[
{
'AttributeName': 'mall',
'KeyType': 'HASH'
},
{
'AttributeName': 'sortkey',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'mall',
'AttributeType': 'S'
},
{
'AttributeName': 'sortkey',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10
}
)
Create Item
response = table.put_item(
Item={
stuff
}
)
Delete
- If using composite key, must supply both hash and range key
- Use ReturnValues param 'ALL_OLD' to have function return deleted item. (Will be in 'Attributes' key of returned object)
response = table.delete_item(
Key={
'id': id,
'sortkey': sortkey
},
ReturnValues='ALL_OLD'
)
Update
Update Nested Attribute
{
'id': 'test'
'Spam': {
'Eggs': {'hello: 'hello'}
}
}
r = table.update_item(Key={'id': 'test'},
UpdateExpression='SET #spa.#egg = :val',
ExpressionAttributeNames={
'#spa': 'Spam',
'#egg': 'Eggs'
},
ExpressionAttributeValues={
':val': {'hello': 'goodbye'}
}
)