如何使用AWS SDK v3的DynamoDBDocumentClient操作DynamoDb集合?
用TypeScript + AWS SDK v3的DynamoDBDocumentClient实现DynamoDB集合操作
DynamoDB支持三种集合类型:StringSet、NumberSet、BinarySet,DynamoDBDocumentClient会自动处理JavaScript集合与DynamoDB原生集合类型的转换,以下是具体操作实现:
前置准备
先安装依赖并初始化DocumentClient:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, PutCommand, UpdateCommand } from "@aws-sdk/lib-dynamodb"; // 初始化客户端 const client = new DynamoDBClient({ region: "your-region" }); const docClient = DynamoDBDocumentClient.from(client);
1. 创建带集合属性的项
直接在PutCommand的Item中使用JavaScript的Set对象,DocumentClient会自动将其转换为DynamoDB对应的集合类型:
const createItemWithSet = async () => { const command = new PutCommand({ TableName: "your-table-name", Item: { id: "item-1", // 主键 tags: new Set(["typescript", "aws", "dynamodb"]), // StringSet类型 scores: new Set([90, 85, 95]), // NumberSet类型 }, }); await docClient.send(command); console.log("带集合的项创建成功"); }; createItemWithSet();
2. 向现有集合属性添加元素
使用UpdateCommand,通过ADD动作追加元素到集合中。注意:ADD会自动去重,重复元素不会被添加:
const addElementsToSet = async () => { const command = new UpdateCommand({ TableName: "your-table-name", Key: { id: "item-1" }, UpdateExpression: "ADD tags :newTags, scores :newScores", ExpressionAttributeValues: { ":newTags": new Set(["serverless"]), // 要添加的StringSet元素 ":newScores": new Set([88]), // 要添加的NumberSet元素 }, ReturnValues: "ALL_NEW", // 返回更新后的完整项,可选 }); const response = await docClient.send(command); console.log("集合元素添加成功,更新后的项:", response.Attributes); }; addElementsToSet();
3. 从现有集合属性移除元素
使用UpdateCommand,通过DELETE动作移除集合中的指定元素:
const removeElementsFromSet = async () => { const command = new UpdateCommand({ TableName: "your-table-name", Key: { id: "item-1" }, UpdateExpression: "DELETE tags :removeTags, scores :removeScores", ExpressionAttributeValues: { ":removeTags": new Set(["aws"]), // 要移除的StringSet元素 ":removeScores": new Set([95]), // 要移除的NumberSet元素 }, ReturnValues: "ALL_NEW", // 返回更新后的完整项,可选 }); const response = await docClient.send(command); console.log("集合元素移除成功,更新后的项:", response.Attributes); }; removeElementsFromSet();
关键注意点
- 集合操作仅支持同类型元素:比如不能向StringSet中添加数字元素
ADD和DELETE动作仅对集合类型生效,对普通属性使用会报错- 如果集合为空,执行DELETE操作后该属性会被从项中移除
内容的提问来源于stack exchange,提问作者Daniel Birowsky Popeski
相关产品推荐
相关产品推荐

