Giter Site home page Giter Site logo

dynamodb-documentclient-cheat-sheet's Introduction

DynamoDB JavaScript DocumentClient cheat sheet

The DynamoDB Document Client is the easiest and most preferred way to interact with a DynamoDB database from a Nodejs or JavaScript application.

This cheat sheet will help you get up and running quickly building applications with DynamoDB in a Nodejs or JavaScript environment.

This is meant to be a concise version of the full documentation located here to help you get productive as quickly as possible.

For more great DynamoDB resources, check out the DynamoDB Guide.

Getting started

  1. Make sure you have the aws-sdk JavaScript SDK installed or available in the environment. If you are using AWS Lambda, this should already be available.
npm install aws-sdk
  1. Import the SDK and create a new DynamoDB document client.
const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

The AWS.DynamoDB.DocumentClient() constructor takes an optional hash of options. For instance, if you are wanting to set the location to a different region than the main AWS configuration, you could pass it in like this:

const docClient = new AWS.DynamoDB.DocumentClient({ region: 'us-east-2' })

Check out the documentation for those options here.

Database operations

The main things you will be doing are interacting with the database in one of the following ways:

put - docs - Creates a new item, or replaces an old item with a new item by delegating to AWS.DynamoDB.putItem().
scan - docs - Returns one or more items and item attributes by accessing every item in a table or a secondary index (limit of 1 MB of data).
get - docs - Returns a single item given the primary key of that item
query - docs - Returns one or more items and item attributes by accessing every item in a table or a secondary index (maximum of 1 MB of data).
delete - docs - Deletes a single item in a table by primary key by delegating to AWS.DynamoDB.deleteItem().
update - docs - Edits an existing item's attributes, or adds a new item to the table if it does not already exist by delegating to AWS.DynamoDB.updateItem().
batchWrite - docs - Puts or deletes multiple items in one or more tables by delegating to AWS.DynamoDB.batchWriteItem().

There are also other methods:

batchGet - Returns the attributes of one or more items from one or more tables by delegating to AWS.DynamoDB.batchGetItem().
createSet - Creates a set of elements inferring the type of set from the type of the first element.
transactGet - Atomically retrieves multiple items from one or more tables (but not from indexes) in a single account and region.
transactWrite - Synchronous write operation that groups up to 10 action requests.

Usage

Put - Creating a new item / replacing an old item with a new item

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Item: {
    id: '001',
    price: 100.0,
    inStock: true,
    name: 'Yeezys',
    sizes: [8, 8.5, 9, 10, 11, 12, 13],
  },
}

docClient.put(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function createItem(itemData) {
  var params = {
    TableName: 'ProductTable',
    Item: itemData,
  }
  try {
    await docClient.put(params).promise()
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const { data } = event.body
    await createItem(data)
    return { body: 'successfully created item' }
  } catch (err) {
    return { error: err }
  }
}

scan - scanning and returning all of the items in the database

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  FilterExpression: '#shoename = :shoename', // optional
  ExpressionAttributeValues: { ':shoename': 'yeezys' }, // optional
  ExpressionAttributeNames: { '#shoename': 'name' }, // optional
}

docClient.scan(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function listItems() {
  var params = {
    TableName: 'ProductTable',
  }
  try {
    const data = await docClient.scan(params).promise()
    return data
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const data = await listItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

get - getting a single item by primary key

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Key: {
    HashKey: 'hashkey',
  },
}

docClient.get(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function getItem(id) {
  var params = {
    TableName: 'ProductTable',
    Key: { id },
  }
  try {
    const data = await docClient.get(params).promise()
    return data
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const data = await getItem(event.item.id)
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

query - Access items from a table by primary key or a secondary index / GSI.

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  IndexName: 'type-index',
  KeyConditionExpression: '#typename = :typename', // this equals "type = hat"
  ExpressionAttributeNames: { '#typename': 'type' },
  ExpressionAttributeValues: { ':typename': 'hat' },
}

docClient.query(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function queryItems(type) {
  var params = {
    TableName: 'ProductTable',
    IndexName: 'type-index',
    ExpressionAttributeNames: { '#typename': 'type' },
    KeyConditionExpression: '#typename = :typename',
    ExpressionAttributeValues: { ':typename': type },
  }
  try {
    const data = await docClient.query(params).promise()
    return data
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const data = await queryItems(event.item.type)
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

delete - Delete a single item

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Key: {
    id: 'my-item-id-to-delete',
  },
}

docClient.delete(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function deleteItem(id) {
  var params = {
    TableName: 'ProductTable',
    Key: { id },
  }
  try {
    await docClient.delete(params).promise()
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    await deleteItem(event.item.id)
    return { body: 'successfully deleted item' }
  } catch (err) {
    return { error: err }
  }
}

update - Update a single item

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Key: { id: 'my-item-id' },
  UpdateExpression: 'set price = :newprice',
  ExpressionAttributeValues: { ':newprice': 100 },
}

docClient.update(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function updateItem(id, price) {
  var params = {
    TableName: 'ProductTable',
    Key: { id },
    UpdateExpression: 'set price = :newprice',
    ExpressionAttributeValues: { ':newprice': price },
  }
  try {
    await docClient.update(params).promise()
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const { id, price } = event.item
    await updateItem(id, price)
    return { body: 'successfully updated item' }
  } catch (err) {
    return { error: err }
  }
}

batchWrite - Seed a table with data

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

// JSON data
const fetchedData = [
  { language: 'JavaScript', isFun: true },
  { language: 'Rust', isFun: true },
]

// format data for docClient
const seedData = fetchedData.map((item) => {
  return {
    PutRequest: {
      Item: item,
    },
  }
})

/* We can only batch-write 25 items at a time,
  so we'll store both the quotient, as well as what's left.
  */

let quotient = Math.floor(seedData.length / 25)
const remainder = (seedData.length % 25)

/* Upload in increments of 25 */

let batchMultiplier = 1
while (quotient > 0) {
  for (let i = 0; i < seedData.length - 1; i += 25) {
    await docClient.batchWrite(
      {
        RequestItems: {
          YOUR_TABLE_NAME: seedData.slice(i, 25 * batchMultiplier),
        },
      },
      (err, data) => {
        if (err) {
          console.log('something went wrong...')
        } else {
          console.log('yay...uploaded!')
        }
      }
    ).promise()
    console.log({ quotient })
    ++batchMultiplier
    --quotient
  }
}

/* Upload the remaining items (less than 25) */]
if(remainder > 0){
  await docClient.batchWrite(
    {
      RequestItems: {
        YOUR_TABLE_NAME: seedData.slice(seedData.length - remainder),
      },
    },
    (err, data) => {
      if (err) {
        console.log('something went wrong...')
      } else {
        console.log('yay...the remainder uploaded!')
      }
    }
  ).promise()
}

dynamodb-documentclient-cheat-sheet's People

Contributors

chamathpali avatar dabit3 avatar mtliendo avatar nosqlknowhow avatar nxtra avatar ryanhinojosa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.