`
sillycat
  • 浏览: 2556863 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

AMAZON DynamoDB(3)CRUD Item

 
阅读更多
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



分享到:
评论

相关推荐

    激增:适用于Elixir的Amazon DynamoDB

    - "amazon-dynamodb":Amazon DynamoDB 是由亚马逊提供的一个完全托管的NoSQL数据库服务,它提供高性能、高可伸缩性和强一致性。 - "ElixirElixir":可能是一个错误标签,应该是强调Elixir语言在此项目中的应用。 ...

    Laravel开发-dynamodb

    在本文中,我们将深入探讨如何在 Laravel 框架中集成和使用 Amazon DynamoDB,一个由 AWS 提供的高性能无服务器数据库服务。标题"laravel-dynamodb"表明我们将在 Laravel 开发环境中应用 DynamoDB,而描述提及了...

    DynamoDBExamples:DynamoDB 的基本操作

    亚马逊DynamoDB是一款高度可扩展、高性能的NoSQL数据库服务,由亚马逊AWS提供。这个名为"DynamoDBExamples"的项目专注于展示如何进行DynamoDB的基本操作,包括创建(Create)、读取(Read)、更新(Update)和删除...

    dynamodb_node:Dynamodb Node JS示例

    在AWS(亚马逊网络服务)的云数据库服务中,DynamoDB是一个高性能、完全托管的NoSQL数据库。它提供了一种简单的方式来存储和检索大规模的数据,适用于各种应用程序,如移动应用、游戏、Web应用等。本示例主要涉及...

    orbit-dynamodb:适用于Orbit框架的DynamoDB存储扩展

    3. **操作接口**:Orbit DynamoDB提供了丰富的操作接口,例如`putItem`(插入或更新项)、`getItem`(获取项)、`deleteItem`(删除项)和`batchWriteItem`(批量写入项)。开发者可以利用这些接口轻松地进行CRUD...

    Python库 | boto3-1.20.41.tar.gz

    对于NoSQL数据库DynamoDB,boto3提供了一套完整的CRUD(创建、读取、更新、删除)操作。 ```python dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('table_name') response = table.put_item(Item=...

    DynamoDB:DynamoDB的C#代码

    3. **创建表**:在DynamoDB中,你可以使用`CreateTableRequest`对象定义表结构,包括主键(Partition Key和可选的Sort Key)。然后,通过`AmazonDynamoDBClient.CreateTableAsync`方法发送请求。例如,如果你有一个...

    CoffeePJT_DynamoDB

    在当今的云计算时代,Amazon DynamoDB作为一款由亚马逊提供的高性能、完全托管的NoSQL数据库服务,深受开发者喜爱。本项目"CoffeePJT_DynamoDB"正是一个利用JavaScript与DynamoDB进行交互的实际案例,旨在帮助开发者...

    法拉第:Clojure的DynamoDB客户端

    3. **CRUD操作**:Faraday支持创建(Create)、读取(Read)、更新(Update)和删除(Delete)DynamoDB中的数据。例如,`put-item`用于插入新项,`get-item`用于获取项,`update-item`用于修改项,而`delete-item`则...

    dynamodb_demo

    DynamoDB是Amazon Web Services(AWS)提供的一款全托管型NoSQL数据库服务,以其高性能、可扩展性和易用性深受开发者喜爱。在这个“dynamodb_demo”项目中,我们将深入探讨如何使用Python与DynamoDB进行交互,实现...

    dynamodb:DynamoDB API 版本 2012-08-10 的完整客户端实现以及项目和 go 值(结构)之间的映射方法

    2. **操作接口**:库可能提供了一系列的方法,如`GetItem`、`PutItem`、`UpdateItem`、`DeleteItem`等,对应于DynamoDB的基本CRUD操作。这些方法接收结构体实例,自动处理数据转换和请求发送。 3. **查询和扫描**:...

    CRUD_LND:CRUD使用ando Node.js-Dynamo-Lambda

    本项目"CRUD_LND"重点展示了如何利用Amazon Web Services(AWS)的Lambda无服务器计算服务、Node.js编程语言以及DynamoDB NoSQL数据库来实现这些操作。下面将详细解释其中涉及的关键知识点。 首先,Node.js是...

    dynosaur:简单干净的基于Promise的DynamoDB库

    `Dynosaur` 是一个针对 Amazon DynamoDB 的轻量级、易用的 JavaScript 库,它充分利用了 Promise 的特性,为开发者提供了简洁且高效的 API 来操作 DynamoDB 数据存储。DynamoDB 是亚马逊云服务(AWS)提供的一种高性能...

    SimpleGoApiWithDynamo:使用mux和AWS DynamoDB的Simple Rest API

    3. `dynamodb.go`:包含与DynamoDB交互的逻辑,如创建表、插入、查询、更新和删除数据的函数。 4. `config.go`:配置文件,可能包含AWS的访问密钥和秘密访问密钥,以及DynamoDB表格名称等信息。 通过这样的实现,...

    棉花糖-pynamodb:PynamoDB与棉花糖集成

    PynamoDB支持所有DynamoDB的基本操作,包括CRUD(创建、读取、更新、删除)以及查询和扫描等。 二、棉花糖(Marshmallow):数据序列化的利器 棉花糖是一个用于数据验证和序列化的库,广泛应用于API接口的输入输出...

    LIG

    在本场景中,它似乎与Amazon DynamoDB关联,这是一个由亚马逊云服务(AWS)提供的完全托管的NoSQL数据库服务,设计用于提供高吞吐量、低延迟的数据访问。DynamoDB特别适合构建实时应用程序,如移动应用、游戏、流...

    boto3:适用于Python的AWS开发工具包

    Boto3是Amazon Web Services(AWS)为Python编程语言设计的官方SDK(软件开发工具包)。它提供了全面的接口,允许开发者轻松地与各种AWS服务进行交互,包括EC2(Elastic Compute Cloud)、S3(Simple Storage ...

    我的目录

    5. **执行CRUD操作**:通过Java方法调用执行CRUD操作,如`putItem()`(创建)、`getItem()`(读取)、`updateItem()`(更新)和`deleteItem()`(删除)。 6. **错误处理和性能优化**:处理可能出现的异常,如权限...

    okky-comment

    开发者可以通过定义Item(表项)、AttributeValues(属性值)以及KeySchema(键模式)来构建和操作DynamoDB表格。例如,为了存储评论,可能需要定义一个包含用户ID、评论内容、评论时间等属性的表格结构。 对于评论...

Global site tag (gtag.js) - Google Analytics