当前位置: 首页 > 软件库 > 云计算 > >

dynamodb-documentclient-cheat-sheet

DynamoDB JavaScript DocumentClient cheat sheet
授权协议 Readme
开发语言 JavaScript
所属分类 云计算
软件类型 开源软件
地区 不详
投 递 者 於子晋
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

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()
}
 相关资料
  • 我使用DocumentClient(http://docs.aws.amazon.com/awsjavascriptsdk/latest/aws/DynamoDB/DocumentClient.html)来简化DynamoDB的使用。然而,它似乎在使用日期对象时遇到了麻烦。我知道DynamoDB希望日期专门格式化。 这一项不包括DyanmoDB项中的。 这一个将包括它:

  • CHEAT 是一个微型的 C 语言单元测试框架。没有任何依赖和安装配置,使用简单只需一个头文件和一个测试用例即可,示例代码: #include <cheat.h>CHEAT_TEST(mathematics_still_work,    cheat_assert(2 + 2 == 4);    cheat_assert_not(2 + 2 == 5);)

  • Cheat Engine 是一款开源的内存修改工具 ,它允许你修改游戏或软件内存数据,以达到各种非常规目的。 它包括16进制编辑,反汇编程序,内存查找工具。 它功能丰富专业,与同类修改工具相比,更像是一个Crack工具。 它具有强大的反汇编功能,且自身附带了外挂制作工具,甚至可用之直接生成修改器。 它具有良好的64位支持。支持插件,在官方网站可找到大量现成的游戏 Cheat Tables。

  • Cheat Sheets A searchable site of hints and tips! Image Credit ccbyplz A place for all my cheat sheets to live! This is a list of stuff that I have put down that I continuallyreference. Current list o

  • Linux 命令行的强大在于其灵活及多样化,各个Linux命令都带有它自己专属的命令行选项和参数。混合并匹配这些命令,甚至还可以通过管道和重 定向来联结不同的命令。理论上讲,你可以借助几个基本的命令来产生数以百计的使用案例。甚至对于浸淫多年的管理员而言,也难以完全使用它们。那正是命令行小抄成为我们救命稻草的一刻。 我知道联机手册页(man)仍然是我们的良师益友,但我们想通过我们能自行支配的快速参考

  • Concise Cheat Sheets This repository is a collection of Cheat Sheets for programming languages andtools. Currently: A Haskell Cheat Sheet -- version 1.1 A Python Cheat Sheet -- version 0.1 (work in pr