![](/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.