![](/img/trans.png)
[英]How do I add a list of dict to DynamoDB using the put_item method in boto3
[英]How to get this list of dict in DynamoDB using boto3?
这是我想在 DynamoDB 中添加的项目示例:
第 1 项:
user :{'Id': '123456789', 'Name': 'user2', 'Keys': [{'KeyId': '987654321', 'keyStatus': 'Active'}]}
第 2 项:
user :{'Id': '59940303', 'Name': 'user2', 'Keys': [{'KeyId': '987654321', 'keyStatus': 'Active'},{'KeyId': '6382920434', 'keyStatus': 'Active'}]}
如您所见,Keys 部分包含一个字典列表。 Item1
包含一个字典, item2
包含两个字典。
如何在 DynamoDB 中添加它?
这有效(没有字典列表):
table = dynamodb_resource.Table("name")
table.update_item(
TableName=table_name,
Key={"Id": user["Id"]},
UpdateExpression="set Name=:n",
ExpressionAttributeValues={
":n": user["Name"]
},
ReturnValues="UPDATED_NEW"
但是我应该如何更新这个字典列表?
更新对我来说很好,如下所示:
table.update_item(
Key={"id": user["Id"]},
UpdateExpression="set #n=:n, #k=:k",
ExpressionAttributeValues={":n": user["Name"], ":k": user["Keys"]},
ExpressionAttributeNames={"#n": "Name", "#k": "Keys"},
ReturnValues="UPDATED_NEW",
)
这是一个工作示例:
from boto3.dynamodb.conditions import Key
users = [
{"Id": "A123456789", "Name": "user1", "Keys": [{"KeyId": "A987654321", "keyStatus": "Active"}],},
{ "Id": "B123456789", "Name": "user2", "Keys": [{"KeyId": "Z987654321", "keyStatus": "Active"},{"KeyId": "C6382920434", "keyStatus": "Active"},],},
]
# create the two records
for user in users:
tbl.update_item(
Key={
"Id": user["Id"],
},
UpdateExpression="set #name=:n, #keys=:k",
ExpressionAttributeValues={
":n": user["Name"],
":k": user["Keys"],
},
ExpressionAttributeNames={"#name": "Name", "#keys": "Keys"}, # fields are reserved keywords! we must use substitution
ReturnValues="UPDATED_NEW",
)
# query a record
res = tbl.query(KeyConditionExpression=Key('Id').eq('B123456789'))
print(res["Items"][0])
# {'Id': 'B123456789', 'Keys': [{'keyStatus': 'Active', 'KeyId': 'Z987654321'}, {'keyStatus': 'Active', 'KeyId': 'C6382920434'}], 'Keys[0].keyStatus': 'Inactive', 'Name': 'user2'}
# update a nested attribute - set the first key status to inactive
tbl.update_item(
Key={"Id": "B123456789"},
UpdateExpression="set #keys[0].#status=:s",
ExpressionAttributeValues={
":s": "Inactive",
},
ExpressionAttributeNames={"#keys": "Keys", "#status": "keyStatus"},
ReturnValues="UPDATED_NEW",
)
# query the updated record again
res = tbl.query(KeyConditionExpression=Key('Id').eq('B123456789'))
print(res["Items"][0])
# {'Id': 'B123456789', 'Keys': [{'KeyId': 'Z987654321', 'keyStatus': 'Inactive'}, {'keyStatus': 'Active', 'KeyId': 'C6382920434'}], 'Name': 'user2'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.