如果该值存在则增加该值,否则在 DynamoDB 中添加一个新条目
Increment the value if it exists, else add a new entry in DynamoDB
我有一个 DynamoDB table,列和主键为 ipAddress
:
- ip地址
- 访问次数
我正在从我的 React 网站获取用户的 IP 地址,并通过 Lambda 函数和 API 网关 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)
};
}
};
我们需要使用 update-item rather than put-item, both creates a record if record doesn't exist. But update-item accepts 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);
}
);
我有一个 DynamoDB table,列和主键为 ipAddress
:
- ip地址
- 访问次数
我正在从我的 React 网站获取用户的 IP 地址,并通过 Lambda 函数和 API 网关 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)
};
}
};
我们需要使用 update-item rather than put-item, both creates a record if record doesn't exist. But update-item accepts 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);
}
);