[英]Dynamically and conditionally update_item on nested DynamoDB dict
I have a DynamoDB table with items in the following format:我有一个 DynamoDB 表,其中包含以下格式的项目:
{
"attributes": {
"cities": {
"oakland": {
"data": "Some stuff."
}
},
"people": {
"Joe": {
"data": "Some stuff."
}
}
}
I have a JSON file (dynamodbupdate.json) that contains the new data I would like to add.我有一个 JSON 文件 (dynamodbupdate.json),其中包含我想添加的新数据。 The structure looks like this:
结构如下所示:
{
"attributes": {
"cities": {
"oakland": {
"data_point_1": "warm"
}
},
"people": {
"Joe": {
"data_point_1": "tall",
"data_point_1": "smart"
}
}
}
I would like to update the table using the update_item action from the boto3 library to add new data to my table without overwriting the existing data.我想使用 boto3 库中的update_item操作更新表,以将新数据添加到我的表中,而不会覆盖现有数据。 I can perform this with a single table item, but I'm trying to find a way to dynamically add new data to several items so that my new table will look like this:
我可以使用单个表项执行此操作,但我正在尝试找到一种将新数据动态添加到多个项的方法,以便我的新表如下所示:
{
"attributes": {
"cities": {
"oakland": {
"data": "Some stuff.",
"data_point_1": "warm"
}
},
"people": {
"Joe": {
"data": "Some stuff."
"data_point_1": "tall",
"data_point_2": "smart"
}
}
}
The UpdateExpression for doing this to a single item would look something like this:对单个项目执行此操作的 UpdateExpression 如下所示:
UpdateExpression = 'SET people.Joe.data_point_1 = if_not_exists(people.Joe.data_point_1, tall)'
However, I would love to find a way to iterate through the entire contents of the dynamodbupdate.json file and issue an an update_item command for all data.但是,我很想找到一种方法来遍历 dynamodbupdate.json 文件的全部内容并为所有数据发出 update_item 命令。
This post comes pretty close to what I need, but I can't wrap my head around the proper way to do it in my example. 这篇文章非常接近我所需要的,但在我的示例中,我无法理解正确的方法。 Thanks for your help!
谢谢你的帮助!
I was able to (mostly) figure this out by doing the following:我能够(大部分)通过执行以下操作来解决这个问题:
def lambda_handler(event, context):
configPath = os.environ['LAMBDA_TASK_ROOT'] + "/dynamodbupdate.json"
configContents = open(configPath).read()
configJson = json.loads(configContents)
ld = configJson.get('attributes').get('cities')
cities_dict = (list(ld))
for x in cities_dict:
all_dp = list(ld.get(x))
for dp in all_dp:
update_query = 'SET #a.#c.#x.#dp = if_not_exists(#a.#c.#x.#dp, :val)'
perform_update = table.update_item(
Key={'primarykey': whateveryourkeyis},
ExpressionAttributeValues={
':val': ld.get(x).get(dp)
},
ExpressionAttributeNames={
'#a': 'attributes',
'#c': 'cities',
'#x': x,
'#dp': dp
},
UpdateExpression=update_query)
I can just loop through the cities/people level and pull that data in, as well.我也可以循环遍历城市/人员级别并提取该数据。 Hope this helps someone!
希望这可以帮助某人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.