DynamoDB:集合的 list_append 替代方案 [英] DynamoDB: list_append alternative for sets
问题描述
我正在尝试对 dynamodb 字符串集属性执行更新操作.对于列表,操作将是
I am trying to do an update operation on a dynamodb string set attribute. For lists, the operation would be
set #key = list_append(if_not_exists(#key, :empty_list), :newValue)
但这会产生一个列表属性.除了 set 之外,list_append 还有其他选择吗?
But this produces a list attribute. Is there an alternative for list_append but for sets?
推荐答案
由于 DynamoDB 无法存储空集,这实际上相当简单,您只需使用 ADD
operator.
Since DynamoDB can't store empty sets this is actually fairly easy, you can just use the ADD
operator.
这是我用 Python 构建的示例:
Here's an example I've built in 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 知道它需要将其转换为一个集合.
In python it's sufficient to pass a value with the datatype set in the ExpressionAttributeValues
for boto3 to know it needs to convert it into a set under the hood.
当我第一次调用 add_to_set
时,它会创建 set 属性,后续调用只是对属性的更新.
When I call add_to_set
for the first time, it will create the set attribute and subsequent calls are just updates to the attribute.
这就是项目最后的样子:
This is what the item looks like in the end:
{
"PK": {
"S": "ITEM#a"
},
"SK": {
"S": "METADATA"
},
"values": {
"SS": [
"value_1",
"value_2"
]
}
}
这篇关于DynamoDB:集合的 list_append 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!