[英]Unable to delete item from DynamoDB StringSet with boto3
I have a table that contains an attribute of type StringSet.我有一个包含 StringSet 类型属性的表。 The attributes name is
allDevices
.属性名称是
allDevices
。 I am trying to remove a device id from the StringSet.我正在尝试从 StringSet 中删除设备 ID。 However, when I run the below code, it does not remove the string from the StringSet.
但是,当我运行以下代码时,它不会从 StringSet 中删除字符串。 It also does not throw any error.
它也不会抛出任何错误。 When attempting to remove deviceID
fakeID1
response is :当尝试删除 deviceID
fakeID1
响应是:
{'Attributes': {'allDevices': {'fakeID1', 'fakeID2'}}, 'ResponseMetadata': {'RequestId': '<removed>', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Fri, 22 Feb 2019 09:04:52 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '93', 'connection': 'keep-alive', 'x-amzn-requestid': '<removed>', 'x-amz-crc32': '<removed>'}, 'RetryAttempts': 0}}
How do I get DynamoDB to remove a string from the StringSet?如何让 DynamoDB 从 StringSet 中删除字符串?
Python Code:蟒蛇代码:
dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('sniffer-users') try: response = table.update_item( Key={ 'username': user, }, UpdateExpression="DELETE allDevices :s", ExpressionAttributeValues={ ':s': set(deviceID), }, ReturnValues="UPDATED_NEW" ) print(response) except ClientError as e: print(e.response['Error']['Message']) return -9
Things I have tried:我尝试过的事情:
set()
from around deviceIDset()
DELETE
to REMOVE
DELETE
来REMOVE
fakeID1
to make it read ':s': set('fakeID1'),
fakeID1
使其读取':s': set('fakeID1'),
':s': {'SS': [oldDeviceID]},
':s': {'SS': [oldDeviceID]},
allDevices
is the same in code as on DDBallDevices
的代码与 DDB 上的相同allDevices
- this works flawlesslyallDevices
添加一些东西 - 这完美无缺You just need to make a minor modification to your ExpressionAttributeValues.您只需要对您的 ExpressionAttributeValues 稍作修改。 To convert a single string into a set, you must first make it a list.
要将单个字符串转换为集合,您必须首先将其设为列表。
ExpressionAttributeValues={
':s': set([deviceID]),
}
Notice the difference below between putting your variable inside [] to make it list and not doing so.请注意以下将变量放入 [] 以使其列出与不这样做之间的区别。
>>> deviceID = "WB529"
>>> set(deviceID)
set(['9', '2', 'B', '5', 'W'])
>>> set([deviceID])
set(['WB529'])
This delete operation will indicate it is successful and return "updated" attributes even if no changes have been made.即使没有进行任何更改,此删除操作也将表明它成功并返回“已更新”属性。 I have some really similar code;
我有一些非常相似的代码; it is impossible to tell from the response if you removed an element from the stringset or if it was never there to begin with.
从响应中无法判断您是否从字符串集中删除了一个元素,或者它是否从一开始就不存在。
I haven't tried it, but I believe that adding a ConditionExpression will give you that feedback (the operation will either succeed or will throw an exception).我还没有尝试过,但我相信添加 ConditionExpression 会给你反馈(操作要么成功,要么抛出异常)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.