【问题标题】:How to insert json in dynamodb如何在dynamodb中插入json
【发布时间】:2016-01-01 21:25:00
【问题描述】:

这是我的代码。
我想将asset_data json 插入asset_data 列。 我正在使用 aws sdk。 它说 aws sdk 现在支持 json。 http://aws.amazon.com/releasenotes/SDK/JavaScript/1691866671551861

var asset_data = {
    "name": "name" + i,
    "contentUrl": "http://www.hdwallpapersimages.com/nature-beauty-desktop-images/94892/",
    "size": 300,
    "headline": "headline",
    "description": "assetUrl reference for the creator",
    "encodingFormat": 'jpeg'
  };

  var params = {
    TableName: 'xyz',
    Item: { // a map of attribute name to AttributeValue
      "asset_id": {S: "asset" + i},
      "hit_id": {S: "0"},
      "created_date": {"S": Date.now().toString()},
      "status": {N: "0"},
      "operation": {S: "image_tagging"},
      "asset_data": {L: asset_data},
      "source": {S: "DAM"},
      "completed_date": {S: Date.now().toString()},
      "response_data": {S: "taged value"}
      // more attributes...
    },

    ReturnValues: 'NONE', // optional (NONE | ALL_OLD)
    ReturnConsumedCapacity: 'NONE', // optional (NONE | TOTAL | INDEXES)
    ReturnItemCollectionMetrics: 'NONE' // optional (NONE | SIZE)
  };

  db.putItem(params, function (err, data) {
    if (err) console.log(err); // an error occurred
    else console.log("inserted..."); // successful response
  });

【问题讨论】:

    标签: node.js amazon-web-services amazon-dynamodb aws-sdk


    【解决方案1】:

    您可以使用 DynamoDB 文档客户端 SDK:

    http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property

    文档客户端简化了对 Amazon DynamoDB 中项目的处理 通过抽象出属性值的概念。这种抽象 注释作为输入参数提供的本机 JavaScript 类型,如 以及将带注释的响应数据转换为原生 JavaScript 类型。

    对于您的情况,请特别查看以下示例中从官方文档中提取的 Map Attribute 值 (M) 被传递为 MapAttribute。文档客户端 API 负责 Javascript 和 DynamoDB 类型之间的正确编组/解组(这意味着您不必指定 Attribute Values (S,N,L,...),因为它在使用非基于文档的 SDK 时是必需的):

    var params = {
      TableName: 'Table',
      Item: {
         HashKey: 'haskey',
         NumAttribute: 1,
         BoolAttribute: true,
         ListAttribute: [1, 'two', false],
         MapAttribute: { foo: 'bar'},
         NullAttribute: null
      }
    };
    
    var docClient = new AWS.DynamoDB.DocumentClient();
    
    docClient.put(params, function(err, data) {
      if (err) console.log(err);
      else console.log(data);
    });
    

    【讨论】:

    • 有没有办法从 CLI 使用这个 DocumentClient() 东西来做一个放置项?在文档中看不到。谢谢!
    【解决方案2】:

    DynamoDB 可以存储 JSON 数据,也可以存储您希望插入的数据格式。 有两种方法可用于在插入 DynamoDB 时格式化数据,以及将数据库数据检索为所需的 JSON 方法。 https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html 这些方法是:inputoutput

    我已经分享了两个 AWS lambda 代码示例 sn-ps,希望这能解决您的问题。

    您可以通过以下方式将 JSON 数据转换为 DynamoDB 支持的格式,然后插入:

    const AWS = require('aws-sdk');
    //setting the region
    AWS.config.update({region: 'ap-south-1'});
    
    // Create the DynamoDB service object
    const ddb = new AWS.DynamoDB.DocumentClient();
    
    
    const getParams = (updatedTasks)=>{
    const params = {
      TableName: 'todo-application',
      Key: {
        "userID" : "anandujjwal13@gmail.com",
      },
      UpdateExpression: "set tasks = :updatedTasks",
       ExpressionAttributeValues:{
            ":updatedTasks":updatedTasks
        },
        ReturnValues:"UPDATED_NEW"
    };
    return params;
    }
    
    const dbQuery =(newTask)=>{
        let updatedTask = AWS.DynamoDB.Converter.input(newTask, true);
        console.log('updated task formatted ',updatedTask);
     let params = getParams(updatedTask);
      return new Promise((resolve,reject) =>{
      ddb.update(params, function(err, data) {
      if (err) {
        console.log("Error", err);
        reject(err);
      } else {
        console.log("Success", data);
        resolve(data.Item)
      }
    });
    });
    }
    
    
    exports.updateTodoJobsOfAUser = async (event) => {
        const insertObject = [
        {
        statement:'learn Dynamo DB', id: 23
        },
        {
        statement:'Learn Serverless Architecture',id:24 
        }]
        const data = await dbQuery(insertObject);
        const response = {
            statusCode: 200,
            body: JSON.stringify(data)
        };
        return response;
    };

    您可以通过以下方式将 DynamoDB 数据转换为 JSON 格式:

    const dbQuery =()=>{
      return new Promise((resolve,reject) =>{
      ddb.get(params, function(err, data) {
      if (err) {
        console.log("Error", err);
        reject(err);
      } else {
        console.log("Success", data);
        resolve(data.Item)
      }
    });
    });
    }
    
    
    exports.getAllTodoJobsOfAUser = async (event) => {
        const data = await dbQuery();
        const formattedData =  AWS.DynamoDB.Converter.output(data, true);
        const response = {
            statusCode: 200,
            body: JSON.stringify(formattedData)
        };
        return response;
    };

    它对我有用。 乐意效劳 !! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 2021-07-09
      • 2020-08-16
      相关资源
      最近更新 更多