DynamoDB Reference Codes - sanket143/DynamoDB-Lab GitHub Wiki

DynamoDB Manual

Create Table

# app_create.py
import boto3

def create_table(table_name):
  dynamodb.create_table(
    TableName=table_name,
    KeySchema=[
      {
          'AttributeName': 'publisher',
          'KeyType': 'HASH'  # Partition key
      },
      {
          'AttributeName': 'title',
          'KeyType': 'RANGE'  # Sort key
      }
    ],
    AttributeDefinitions=[
      {
          'AttributeName': 'publisher',
          'AttributeType': 'S'
      },
      {
          'AttributeName': 'title',
          'AttributeType': 'S'
      },
      {
          'AttributeName': 'isbn',
          'AttributeType': 'S'
      }
    ],
    GlobalSecondaryIndexes=[
      {
        'IndexName': 'isbn-index',
        'KeySchema': [
          {
            'KeyType': 'HASH',
            'AttributeName': 'isbn'
          }
        ],
        'Projection': {
          'ProjectionType': 'ALL'
        },
        'ProvisionedThroughput': {
          'ReadCapacityUnits': 10,
          'WriteCapacityUnits': 10
        }
      }
    ],
    ProvisionedThroughput={
      'ReadCapacityUnits': 10,
      'WriteCapacityUnits': 10
    }
  )

if __name__ == "__main__":
  dynamodb = boto3.resource('dynamodb', region_name='ap-south-1', endpoint_url="http://localhost:8000")
  table_name = "Books"
  try:
    resp = dynamodb.Table(table_name).load()
    print("Table Books already exists")

  except:
    create_table(table_name)
# create table
aws dynamodb create-table \
    --table-name Books \
    --attribute-definitions \
        AttributeName=publisher,AttributeType=S \
        AttributeName=title,AttributeType=S \
        AttributeName=isbn,AttributeType=S \
    --key-schema \
        AttributeName=publisher,KeyType=HASH \
        AttributeName=title,KeyType=RANGE \
    --global-secondary-indexes \
        IndexName=isbn-index,KeySchema=["{AttributeName=isbn,KeyType=HASH}"],Projection="{ProjectionType=ALL}",ProvisionedThroughput="{ReadCapacityUnits=10,WriteCapacityUnits=10}" \
--provisioned-throughput \
        ReadCapacityUnits=10,WriteCapacityUnits=5 \
        --endpoint-url http://localhost:8000

Put Item

# app_put.py
import boto3
import json

def putItem(table_name, content):
  table = dynamodb.Table(table_name)
  response = table.put_item(Item=content)
  return response

if __name__ == "__main__":
  dynamodb = boto3.resource('dynamodb', region_name='ap-south-1', endpoint_url="http://localhost:8000")

  fd = open("data/books.json", "r")
  books_obj = json.loads(fd.read())
  obj = books_obj["books"][0]
  print(putItem("Books", obj))
# put item
aws dynamodb put-item \
    --table-name Books \
    --item '{"isbn": {"S": "9781491904244"}, "title": {"S": "You Dont Know JS"}, "subtitle": {"S": "ES6 & Beyond"}, "author": {"S": "Kyle Simpson"}, "published": {"S": "2015-12-27T00:00:00.000Z"}, "publisher": {"S": "O''Reilly Media"}, "pages": {"N": "278"}, "description": {"S": "Test Descripton, Dont Know JS"}, "website": {"S": "https://github.com/getify"} }' \
    --return-consumed-capacity TOTAL \
    --endpoint-url http://localhost:8000

Batch Write

# app_batch_write.py
import boto3
import json

def batchWrite(table_name, contents):
  table = dynamodb.Table(table_name)

  with table.batch_writer() as batch:
    for item in contents:
      batch.put_item(Item=item)

if __name__ == "__main__":
  dynamodb = boto3.resource('dynamodb', region_name='ap-south-1', endpoint_url="http://localhost:8000")

  fd = open("data/books.json", "r")
  books_obj = json.loads(fd.read())

  obj = books_obj["books"][1:100]
  batchWrite("Books", obj)
# batch write item
aws dynamodb batch-write-item \
  --request-items file:///home/sanket143/Verts/DynamoDB/cli/request-items.json \
  --endpoint-url http://localhost:8000

Get Item

# app_get.py
import boto3
import json

def getItem(table_name, key):
  table = dynamodb.Table(table_name)
  response = table.get_item(Key=key)
  return response["Item"]

if __name__ == "__main__":
  dynamodb = boto3.resource('dynamodb', region_name='ap-south-1', endpoint_url="http://localhost:8000")Scripts for operations on DynamoDB
  obj = {
    "title": "Designing Evolvable Web APIs with ASP.NET",
    "publisher": "O'Reilly Media"
  }
  print(getItem("Books", obj))
# get item
aws dynamodb get-item --consistent-read \
    --table-name Books \
    --key '{ "publisher": {"S": "No Starch Press"}, "title": {"S": "Eloquent JavaScript, Second Edition"}}' \
    --endpoint-url http://localhost:8000

Get Using GSI

# app_get_second.py
import boto3
import json
from boto3.dynamodb.conditions import Key

def queryItem(table_name, val):
  table = dynamodb.Table(table_name)
  response = table.query(IndexName="isbn-index", KeyConditionExpression=Key("isbn").eq(val))
  return response["Items"]

if __name__ == "__main__":
  dynamodb = boto3.resource('dynamodb', region_name='ap-south-1', endpoint_url="http://localhost:8000")
  print(queryItem("Books", "9781449337711"))
aws dynamodb query \
    --table-name Books \
    --index-name isbn-index \
    --key-condition-expression "#k1 = :v1" \
    --expression-attribute-names '{"#k1": "isbn"}' \
    --expression-attribute-values '{":v1": {"S": "9781593275846"}}' \
    --endpoint-url http://localhost:8000

Update Item

# app_update.py
import boto3
import json

def updateItem(table_name, keyVal, updatedVal):
  key, value = updatedVal
  table = dynamodb.Table(table_name)
  table.update_item(
    Key=keyVal,
    UpdateExpression="SET #key = :val",
    ExpressionAttributeNames={
      "#key": key,
    },
    ExpressionAttributeValues={
      ":val": value
    }
  )

if __name__ == "__main__":
  dynamodb = boto3.resource('dynamodb', region_name='ap-south-1', endpoint_url="http://localhost:8000")

  keyVal = {
    "title": "Git Pocket Guide",
    "publisher": "O'Reilly Media"
  }

  updatedVal = ["author", "Linus Torvalds"]
  updateItem("Books", keyVal, updatedVal)
# update item
aws dynamodb update-item \
    --table-name Books \
    --key '{ "title": {"S": "Speaking JavaScript"}, "publisher": {"S": "O'"'"'Reilly Media"}}' \
    --update-expression "SET author = :newval" \
    --expression-attribute-values '{":newval":{"S":"Linus Torvalds"}}' \
    --return-values ALL_NEW \
    --endpoint-url http://localhost:8000
⚠️ **GitHub.com Fallback** ⚠️