【问题标题】:Increment the value if it exists, else add a new entry in DynamoDB如果存在则增加该值,否则在 DynamoDB 中添加一个新条目
【发布时间】:2021-02-22 13:00:09
【问题描述】:

我有一个 DynamoDB 表,其列和主键为 ipAddress

  • ip地址
  • 访问次数

我正在从我的 react 网站获取用户的 IP 地址,并通过 Lambda 函数和 API Gateway POST 请求将其插入到 DynamoDB。

如果来自 React 网站的 IP 地址已经存在于 DynamoDB 中,则增加 visits 列中的值。如果不是,则使用新 IP 地址和visits = 1 创建一条新记录。我尝试使用 ConditionExpression 但无济于事。

到目前为止,我只使用 Lambda 插入 ipAddress。下面是我在 NodeJS 中的 Lambda 函数:

const AWS = require("aws-sdk");
const documentClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async event => {
  const { ipAddress} = JSON.parse(event.body);
  const params = {
    TableName: "ipAddress",
    Item: {
      ipAddress: ipAddress,
    }
  };

  try {
    const data = await documentClient.put(params).promise();
    const response = {
      statusCode: 200,
    };
    return response;
  }
  catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify(e)
    };
  }

};

【问题讨论】:

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


    【解决方案1】:

    我们需要使用update-item 而不是put-item,如果记录不存在,两者都会创建记录。但 update-item 接受UpdateExpression 来帮助我们更新现有属性。

    UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num"

    if_not_exists 有助于在 visits 属性不存在时首次使用 initial 值。

    docClient.update(
      {
        TableName: "ipAddress",
        Key: {
          ipAddress: ipAddress,
        },
        UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num",
        ExpressionAttributeValues: {
          ":num": 1,
          ":initial": 0,
        },
      },
      function (error, result) {
        console.log("error", error, "result", result);
      }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多