我正在尝试对 dynamodb 字符串集属性执行更新操作。对于列表,操作将是
set #key = list_append(if_not_exists(#key, :empty_list), :newValue)
但这会产生一个列表属性。除了 set 之外,list_append 还有其他选择吗?
答案 0 :(得分:1)
由于 DynamoDB 无法存储空集,这实际上相当简单,您只需使用 ADD
operator。
这是我用 Python 构建的示例:
import boto3
TABLE_NAME = "set-demo"
def create_table():
ddb = boto3.client("dynamodb")
ddb.create_table(
AttributeDefinitions=[
{"AttributeName": "PK", "AttributeType": "S"},
{"AttributeName": "SK", "AttributeType": "S"}
],
TableName=TABLE_NAME,
KeySchema=[
{"AttributeName": "PK", "KeyType": "HASH"},
{"AttributeName": "SK", "KeyType": "RANGE"}
],
BillingMode="PAY_PER_REQUEST"
)
def add_to_set(item_id: str, value: str):
table = boto3.resource("dynamodb").Table(TABLE_NAME)
table.update_item(
Key={
"PK": f"ITEM#{item_id}",
"SK": f"METADATA",
},
UpdateExpression="ADD #set_name :set_value",
ExpressionAttributeNames={
"#set_name": "values"
},
ExpressionAttributeValues={
":set_value": {value}, # needs to be a set type
}
)
if __name__ == "__main__":
# create_table()
add_to_set("a", "value_1")
add_to_set("a", "value_2")
add_to_set("a", "value_1")
在 python 中,传递一个在 ExpressionAttributeValues
中设置的数据类型的值就足以让 boto3 知道它需要将其转换为一个集合。
当我第一次调用 add_to_set
时,它会创建 set 属性,后续调用只是对该属性的更新。
这就是项目最后的样子:
{
"PK": {
"S": "ITEM#a"
},
"SK": {
"S": "METADATA"
},
"values": {
"SS": [
"value_1",
"value_2"
]
}
}