- 浏览: 2556831 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
AMAZON DynamoDB(3)CRUD Item
BatchWriteItem we are using that to save data into DynamoDB. But BatchWriteItem cannot update items, to update items, use the UpdateItem action.
DynamoDB Operation List
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations.html
How to Truncate all data in one table
https://gist.github.com/k3karthic/4bc929885eef40dbe010
We can delete the unused columns if we need to
delete item.serialNumber1;
Here is some code to do that thing
"use strict";
// How to run
// eg: node dynamodb-scripts/import-devices-to-dynamodb.js int ./css_devices_only_csv.txt
var importDevicesToDynamo;
(function (importDevicesToDynamo) {
const fs = require('fs');
const babyparse = require("babyparse");
const AWS = require("aws-sdk");
const log4js = require('log4js');
const logger = log4js.getLogger();
const sleep = require('sleep');
const DEV_DYNAMODB_URL = "http://dynamodb.us-west-1.amazonaws.com";
const DEV_DYNAMO_ACCESS_KEY = "xxxxx";
const DEV_DYNAMO_SECRET_KEY = "xxxxxx/xxx";
const DEV_DYNAMO_REGION = "us-west-1";
const STAGE_DYNAMODB_URL = "http://dynamodb.us-west-1.amazonaws.com";
const STAGE_DYNAMO_ACCESS_KEY = "xxxxxxx";
const STAGE_DYNAMO_SECRET_KEY = "xxxxx/xxxxxxx";
const STAGE_DYNAMO_REGION = "us-west-1";
const PROD_DYNAMODB_URL = "http://dynamodb.us-west-2.amazonaws.com";
const PROD_DYNAMO_ACCESS_KEY = "xxxxxx";
const PROD_DYNAMO_SECRET_KEY = "xxxxxxxxxxxx";
const PROD_DYNAMO_REGION = "us-west-2";
const env = process.argv[2]; // Must be int, stage or prod
const csvFilePath = process.argv[3];
const config = {
delimiter: ',',
newline: "",
quoteChar: '"',
header: true,
dynamicTyping: false,
preview: 0,
encoding: "utf8",
worker: false,
comments: false,
skipEmptyLines: true
};
let tableName = `sillycat_device-${env}-devicePairing`;
let accessKey = "";
let signatureKey = "";
let region = "";
let dynamoDbUrl = "";
//validate parameters
if (!env) {
console.log("\nMust pass in environment for 1st argument. Must be one of 'int, 'stage' or 'prod'");
console.log("\nUsage - node dynamodb-scripts/import-devices-to-dynamodb.js {env} {csv path/file } ");
console.log("\nExample - node dynamodb-scripts/import-devices-to-dynamodb.js int ./css_devices_only_csv.txt \n");
process.exit(1);
}
if (!csvFilePath) {
console.log("\nMust pass in csvFilePath for 2nd argument.");
console.log("\nUsage - node dynamodb-scripts/import-devices-to-dynamodb.js {env} {csv path/file } ");
console.log("\nExample - node dynamodb-scripts/import-devices-to-dynamodb.js int ./css_devices_only_csv.txt \n");
process.exit(2);
}
if (env.toLowerCase() === 'int' || env.toLowerCase() === 'test') {
dynamoDbUrl = DEV_DYNAMODB_URL;
accessKey = DEV_DYNAMO_ACCESS_KEY;
signatureKey = DEV_DYNAMO_SECRET_KEY;
region = DEV_DYNAMO_REGION;
} else if (env.toLowerCase() === 'stage') {
dynamoDbUrl = STAGE_DYNAMODB_URL;
accessKey = STAGE_DYNAMO_ACCESS_KEY;
signatureKey = STAGE_DYNAMO_SECRET_KEY;
region = STAGE_DYNAMO_REGION;
} else if (env.toLowerCase() === 'prod') {
dynamoDbUrl = PROD_DYNAMODB_URL;
accessKey = PROD_DYNAMO_ACCESS_KEY;
signatureKey = PROD_DYNAMO_SECRET_KEY;
region = PROD_DYNAMO_REGION;
} else {
console.log("Must pass in environment for 1st argument. Must be one of 'int, 'stage' or 'prod'");
process.exit(1);
}
console.log("Env = " + env);
console.log("File to import = " + csvFilePath);
let content = fs.readFileSync(csvFilePath, config);
let parsed = babyparse.parse(content, config);
let rows = JSON.parse(JSON.stringify(parsed.data));
console.log("Row count = " + Object.keys(rows).length);
let _id;
// For the batch size of 10, we need to temporarily change the write capacity units to 50 in DynaoDB for the appropriate table, then reset to default when script is finished
let size = 10;
console.log("dynamoDbURL = " + dynamoDbUrl);
console.log("tableName = " + tableName);
AWS.config.update({
accessKeyId: accessKey,
secretAccessKey: signatureKey,
region: region,
endpoint: dynamoDbUrl
});
const dynamoDb = new AWS.DynamoDB.DocumentClient();
for (let i = 0; i < rows.length; i += size) {
// Slice the array into smaller arrays of 10,000 items
let smallarray = rows.slice(i, i + size);
console.log("i = " + i + " serialNumber = " + smallarray[0].serialNumber);
let batchItems = smallarray.map(function (item) {
try {
// Replace empty string values with null. DynamoDB doesn't allow empty strings, will throw error on request.
for (let items in item) {
let value = item[items];
if (value === undefined || value === "") {
item[items] = null;
}
if (items == "enabled") {
if (value === "f") {
item[items] = false;
} else if (value === "t") {
item[items] = true;
}
}
}
delete item.serialNumber1;
let params = {
PutRequest: { Item: JSON.parse(JSON.stringify(item)) }
};
return params;
}
catch (error) {
console.log("**** ERROR processing file: " + error);
}
});
let batchRequestParams = '{"RequestItems":{"' + tableName + '":' + JSON.stringify(batchItems) + '},"ReturnConsumedCapacity":"TOTAL","ReturnItemCollectionMetrics": "SIZE"}';
console.log("batchRequestParams = " + batchRequestParams);
callDynamo(batchRequestParams).then(function (data) {
sleep.msleep(100);
})
.catch(console.error);
}
function callDynamo(batchRequestParams) {
return new Promise(function (resolve, reject) {
dynamoDb.batchWrite(JSON.parse(batchRequestParams), function (err, data) {
try {
if (err) {
logger.error(`Error - ${err} = Trying again:`);
sleep.msleep(100);
dynamoDb.batchWrite(JSON.parse(batchRequestParams), function (err, data) {
try {
if (err) {
logger.error("Unable to add item a 2nd time, Error:", err);
return reject(err);
}
else {
logger.debug("2nd PutItem succeeded");
resolve(data);
}
}
catch (error) {
console.log("error calling DynamoDB - " + error);
return reject(err);
}
});
}
else {
logger.debug("PutItem succeeded");
resolve(data);
}
}
catch (error) {
console.log("error calling DynamoDB - " + error);
return reject(err);
}
});
});
}
})(importDevicesToDynamo || (importDevicesToDynamo = {}));
References:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html
BatchWriteItem we are using that to save data into DynamoDB. But BatchWriteItem cannot update items, to update items, use the UpdateItem action.
DynamoDB Operation List
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations.html
How to Truncate all data in one table
https://gist.github.com/k3karthic/4bc929885eef40dbe010
We can delete the unused columns if we need to
delete item.serialNumber1;
Here is some code to do that thing
"use strict";
// How to run
// eg: node dynamodb-scripts/import-devices-to-dynamodb.js int ./css_devices_only_csv.txt
var importDevicesToDynamo;
(function (importDevicesToDynamo) {
const fs = require('fs');
const babyparse = require("babyparse");
const AWS = require("aws-sdk");
const log4js = require('log4js');
const logger = log4js.getLogger();
const sleep = require('sleep');
const DEV_DYNAMODB_URL = "http://dynamodb.us-west-1.amazonaws.com";
const DEV_DYNAMO_ACCESS_KEY = "xxxxx";
const DEV_DYNAMO_SECRET_KEY = "xxxxxx/xxx";
const DEV_DYNAMO_REGION = "us-west-1";
const STAGE_DYNAMODB_URL = "http://dynamodb.us-west-1.amazonaws.com";
const STAGE_DYNAMO_ACCESS_KEY = "xxxxxxx";
const STAGE_DYNAMO_SECRET_KEY = "xxxxx/xxxxxxx";
const STAGE_DYNAMO_REGION = "us-west-1";
const PROD_DYNAMODB_URL = "http://dynamodb.us-west-2.amazonaws.com";
const PROD_DYNAMO_ACCESS_KEY = "xxxxxx";
const PROD_DYNAMO_SECRET_KEY = "xxxxxxxxxxxx";
const PROD_DYNAMO_REGION = "us-west-2";
const env = process.argv[2]; // Must be int, stage or prod
const csvFilePath = process.argv[3];
const config = {
delimiter: ',',
newline: "",
quoteChar: '"',
header: true,
dynamicTyping: false,
preview: 0,
encoding: "utf8",
worker: false,
comments: false,
skipEmptyLines: true
};
let tableName = `sillycat_device-${env}-devicePairing`;
let accessKey = "";
let signatureKey = "";
let region = "";
let dynamoDbUrl = "";
//validate parameters
if (!env) {
console.log("\nMust pass in environment for 1st argument. Must be one of 'int, 'stage' or 'prod'");
console.log("\nUsage - node dynamodb-scripts/import-devices-to-dynamodb.js {env} {csv path/file } ");
console.log("\nExample - node dynamodb-scripts/import-devices-to-dynamodb.js int ./css_devices_only_csv.txt \n");
process.exit(1);
}
if (!csvFilePath) {
console.log("\nMust pass in csvFilePath for 2nd argument.");
console.log("\nUsage - node dynamodb-scripts/import-devices-to-dynamodb.js {env} {csv path/file } ");
console.log("\nExample - node dynamodb-scripts/import-devices-to-dynamodb.js int ./css_devices_only_csv.txt \n");
process.exit(2);
}
if (env.toLowerCase() === 'int' || env.toLowerCase() === 'test') {
dynamoDbUrl = DEV_DYNAMODB_URL;
accessKey = DEV_DYNAMO_ACCESS_KEY;
signatureKey = DEV_DYNAMO_SECRET_KEY;
region = DEV_DYNAMO_REGION;
} else if (env.toLowerCase() === 'stage') {
dynamoDbUrl = STAGE_DYNAMODB_URL;
accessKey = STAGE_DYNAMO_ACCESS_KEY;
signatureKey = STAGE_DYNAMO_SECRET_KEY;
region = STAGE_DYNAMO_REGION;
} else if (env.toLowerCase() === 'prod') {
dynamoDbUrl = PROD_DYNAMODB_URL;
accessKey = PROD_DYNAMO_ACCESS_KEY;
signatureKey = PROD_DYNAMO_SECRET_KEY;
region = PROD_DYNAMO_REGION;
} else {
console.log("Must pass in environment for 1st argument. Must be one of 'int, 'stage' or 'prod'");
process.exit(1);
}
console.log("Env = " + env);
console.log("File to import = " + csvFilePath);
let content = fs.readFileSync(csvFilePath, config);
let parsed = babyparse.parse(content, config);
let rows = JSON.parse(JSON.stringify(parsed.data));
console.log("Row count = " + Object.keys(rows).length);
let _id;
// For the batch size of 10, we need to temporarily change the write capacity units to 50 in DynaoDB for the appropriate table, then reset to default when script is finished
let size = 10;
console.log("dynamoDbURL = " + dynamoDbUrl);
console.log("tableName = " + tableName);
AWS.config.update({
accessKeyId: accessKey,
secretAccessKey: signatureKey,
region: region,
endpoint: dynamoDbUrl
});
const dynamoDb = new AWS.DynamoDB.DocumentClient();
for (let i = 0; i < rows.length; i += size) {
// Slice the array into smaller arrays of 10,000 items
let smallarray = rows.slice(i, i + size);
console.log("i = " + i + " serialNumber = " + smallarray[0].serialNumber);
let batchItems = smallarray.map(function (item) {
try {
// Replace empty string values with null. DynamoDB doesn't allow empty strings, will throw error on request.
for (let items in item) {
let value = item[items];
if (value === undefined || value === "") {
item[items] = null;
}
if (items == "enabled") {
if (value === "f") {
item[items] = false;
} else if (value === "t") {
item[items] = true;
}
}
}
delete item.serialNumber1;
let params = {
PutRequest: { Item: JSON.parse(JSON.stringify(item)) }
};
return params;
}
catch (error) {
console.log("**** ERROR processing file: " + error);
}
});
let batchRequestParams = '{"RequestItems":{"' + tableName + '":' + JSON.stringify(batchItems) + '},"ReturnConsumedCapacity":"TOTAL","ReturnItemCollectionMetrics": "SIZE"}';
console.log("batchRequestParams = " + batchRequestParams);
callDynamo(batchRequestParams).then(function (data) {
sleep.msleep(100);
})
.catch(console.error);
}
function callDynamo(batchRequestParams) {
return new Promise(function (resolve, reject) {
dynamoDb.batchWrite(JSON.parse(batchRequestParams), function (err, data) {
try {
if (err) {
logger.error(`Error - ${err} = Trying again:`);
sleep.msleep(100);
dynamoDb.batchWrite(JSON.parse(batchRequestParams), function (err, data) {
try {
if (err) {
logger.error("Unable to add item a 2nd time, Error:", err);
return reject(err);
}
else {
logger.debug("2nd PutItem succeeded");
resolve(data);
}
}
catch (error) {
console.log("error calling DynamoDB - " + error);
return reject(err);
}
});
}
else {
logger.debug("PutItem succeeded");
resolve(data);
}
}
catch (error) {
console.log("error calling DynamoDB - " + error);
return reject(err);
}
});
});
}
})(importDevicesToDynamo || (importDevicesToDynamo = {}));
References:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html
发表评论
-
Stop Update Here
2020-04-28 09:00 320I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 481NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 373Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 373Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 340Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 433Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 441Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 378Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 460VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 390Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 482NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 426Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 340Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 252GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 454GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 330GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 316Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 323Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 298Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 314Serverless with NodeJS and Tenc ...
相关推荐
- "amazon-dynamodb":Amazon DynamoDB 是由亚马逊提供的一个完全托管的NoSQL数据库服务,它提供高性能、高可伸缩性和强一致性。 - "ElixirElixir":可能是一个错误标签,应该是强调Elixir语言在此项目中的应用。 ...
在本文中,我们将深入探讨如何在 Laravel 框架中集成和使用 Amazon DynamoDB,一个由 AWS 提供的高性能无服务器数据库服务。标题"laravel-dynamodb"表明我们将在 Laravel 开发环境中应用 DynamoDB,而描述提及了...
亚马逊DynamoDB是一款高度可扩展、高性能的NoSQL数据库服务,由亚马逊AWS提供。这个名为"DynamoDBExamples"的项目专注于展示如何进行DynamoDB的基本操作,包括创建(Create)、读取(Read)、更新(Update)和删除...
在AWS(亚马逊网络服务)的云数据库服务中,DynamoDB是一个高性能、完全托管的NoSQL数据库。它提供了一种简单的方式来存储和检索大规模的数据,适用于各种应用程序,如移动应用、游戏、Web应用等。本示例主要涉及...
3. **操作接口**:Orbit DynamoDB提供了丰富的操作接口,例如`putItem`(插入或更新项)、`getItem`(获取项)、`deleteItem`(删除项)和`batchWriteItem`(批量写入项)。开发者可以利用这些接口轻松地进行CRUD...
对于NoSQL数据库DynamoDB,boto3提供了一套完整的CRUD(创建、读取、更新、删除)操作。 ```python dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('table_name') response = table.put_item(Item=...
3. **创建表**:在DynamoDB中,你可以使用`CreateTableRequest`对象定义表结构,包括主键(Partition Key和可选的Sort Key)。然后,通过`AmazonDynamoDBClient.CreateTableAsync`方法发送请求。例如,如果你有一个...
在当今的云计算时代,Amazon DynamoDB作为一款由亚马逊提供的高性能、完全托管的NoSQL数据库服务,深受开发者喜爱。本项目"CoffeePJT_DynamoDB"正是一个利用JavaScript与DynamoDB进行交互的实际案例,旨在帮助开发者...
3. **CRUD操作**:Faraday支持创建(Create)、读取(Read)、更新(Update)和删除(Delete)DynamoDB中的数据。例如,`put-item`用于插入新项,`get-item`用于获取项,`update-item`用于修改项,而`delete-item`则...
DynamoDB是Amazon Web Services(AWS)提供的一款全托管型NoSQL数据库服务,以其高性能、可扩展性和易用性深受开发者喜爱。在这个“dynamodb_demo”项目中,我们将深入探讨如何使用Python与DynamoDB进行交互,实现...
2. **操作接口**:库可能提供了一系列的方法,如`GetItem`、`PutItem`、`UpdateItem`、`DeleteItem`等,对应于DynamoDB的基本CRUD操作。这些方法接收结构体实例,自动处理数据转换和请求发送。 3. **查询和扫描**:...
本项目"CRUD_LND"重点展示了如何利用Amazon Web Services(AWS)的Lambda无服务器计算服务、Node.js编程语言以及DynamoDB NoSQL数据库来实现这些操作。下面将详细解释其中涉及的关键知识点。 首先,Node.js是...
`Dynosaur` 是一个针对 Amazon DynamoDB 的轻量级、易用的 JavaScript 库,它充分利用了 Promise 的特性,为开发者提供了简洁且高效的 API 来操作 DynamoDB 数据存储。DynamoDB 是亚马逊云服务(AWS)提供的一种高性能...
3. `dynamodb.go`:包含与DynamoDB交互的逻辑,如创建表、插入、查询、更新和删除数据的函数。 4. `config.go`:配置文件,可能包含AWS的访问密钥和秘密访问密钥,以及DynamoDB表格名称等信息。 通过这样的实现,...
PynamoDB支持所有DynamoDB的基本操作,包括CRUD(创建、读取、更新、删除)以及查询和扫描等。 二、棉花糖(Marshmallow):数据序列化的利器 棉花糖是一个用于数据验证和序列化的库,广泛应用于API接口的输入输出...
在本场景中,它似乎与Amazon DynamoDB关联,这是一个由亚马逊云服务(AWS)提供的完全托管的NoSQL数据库服务,设计用于提供高吞吐量、低延迟的数据访问。DynamoDB特别适合构建实时应用程序,如移动应用、游戏、流...
Boto3是Amazon Web Services(AWS)为Python编程语言设计的官方SDK(软件开发工具包)。它提供了全面的接口,允许开发者轻松地与各种AWS服务进行交互,包括EC2(Elastic Compute Cloud)、S3(Simple Storage ...
5. **执行CRUD操作**:通过Java方法调用执行CRUD操作,如`putItem()`(创建)、`getItem()`(读取)、`updateItem()`(更新)和`deleteItem()`(删除)。 6. **错误处理和性能优化**:处理可能出现的异常,如权限...
开发者可以通过定义Item(表项)、AttributeValues(属性值)以及KeySchema(键模式)来构建和操作DynamoDB表格。例如,为了存储评论,可能需要定义一个包含用户ID、评论内容、评论时间等属性的表格结构。 对于评论...