[英]How to Add item to string_set on Dynamodb with Boto3
I have read the official AWS docs and several forums, still I cant find what I am doing wrong while adding item to string_set using Python/Boto3 and Dynamodb.我已经阅读了 AWS 官方文档和几个论坛,但在使用 Python/Boto3 和 Dynamodb 将项目添加到 string_set 时,我仍然找不到我做错了什么。 Here is my code:
这是我的代码:
table.update_item(
Key={
ATT_USER_USERID: event[ATT_USER_USERID]
},
UpdateExpression="add " + key + " :val0" ,
ExpressionAttributeValues = {":val0" : set(["example_item"]) },
)
The error I am getting is:我得到的错误是:
An error occurred (ValidationException) when calling the UpdateItem operation: An operand in the update expression has an incorrect data type\\"
调用 UpdateItem 操作时发生错误 (ValidationException):更新表达式中的操作数具有不正确的数据类型\\"
It looks like you figured out a method for yourself, but for others who come here looking for an answer:看起来你自己想出了一个方法,但对于来这里寻找答案的其他人:
ExpressionAttributeValues
, andExpressionAttributeValues
使用“SS”作为数据类型,并且ExpressionAttributeValues
.ExpressionAttributeValues
“设置”。 Here's an example I just ran (I had an existing set, test_set, with 4 existing values, and I'm adding a 5th, the string 'five'):这是我刚刚运行的一个示例(我有一个现有的集合 test_set,有 4 个现有值,我正在添加第 5 个,字符串“五”):
import boto3
db = boto3.client("dynamodb")
db.update_item(TableName=TABLE,
Key={'id':{'S':'test_id'}},
UpdateExpression="ADD test_set :element",
ExpressionAttributeValues={":element":{"SS":['five']}})
So before, the string set looked like ['one','two','three','four']
, and after, it looked like ['one','two','three','four','five']
所以之前,字符串集看起来像
['one','two','three','four']
,之后,它看起来像['one','two','three','four','five']
Building off of @joe_stech's answer, you can now do it without having to define the type.基于@joe_stech 的回答,您现在无需定义类型即可完成。
An example is:一个例子是:
import boto3
class StringSetTable:
def __init__(self) -> None:
dynamodb = boto3.resource("dynamodb")
self.dynamodb_table = dynamodb.Table("NAME_OF_TABLE")
def get_str_set(self, key: str) -> typing.Optional[typing.Set[str]]:
response = self.dynamodb_table.get_item(
Key={KEY_NAME: key}, ConsistentRead=True
)
r = response.get("Item")
if r is None:
print("No set stored")
return None
else:
s = r["string_set"]
s.remove("EMPTY_IF_ONLY_THIS")
return s
def add_to_set(self, key: str, str_set: typing.Set[str]) -> None:
new_str_set = str_set.copy()
new_str_set.add("EMPTY_IF_ONLY_THIS")
self.dynamodb_table.update_item(
Key={KEY_NAME: key},
UpdateExpression="ADD string_set :elements",
ExpressionAttributeValues={":elements": new_str_set},
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.