简体   繁体   English

如何从 dynamodb 列表中删除项目

[英]How to delete items from dynamodb list

import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('myowntable')
response = []
response_table = table.get_item(Key={'id': '19'})
        if 'Item' in response_table and response_table['Item']:
            response.append(response_table['Item'])

listofvalues = [1,2,3]
for i in listofvalues:
    id_index_delete = str(response[0]['myList'].index(i))
    query = "REMOVE myList[" + id_index_delete + "]"
    table.update_item(
                    Key={
                        'id': '19'
                    },
                    UpdateExpression=query
                )

You can remove multiple items from a list in a signle operation with an update expression like REMOVE myList[0], myList[2] .您可以使用REMOVE myList[0], myList[2]类的更新表达式在信号操作中从列表中删除多个项目 Here's one way to do it using boto3:这是使用 boto3 的一种方法:

id = 'a1'
response_table = table.get_item(Key={'id': id})
response = response_table.get('Item', {}).get('myList', [])
listofvalues = [1,2,3] # remove these items from myList

items_to_remove = [f'myList[{response.index(x)}]' for x in listofvalues if x in response ]
query = "REMOVE " +  ", ".join(items_to_remove)

if len(items_to_remove):
  table.update_item(Key={'id': id}, UpdateExpression=query)

If you turn your list into a map, you can then delete items based on the map key and do all deletes in one operation.如果将列表转换为地图,则可以根据地图键删除项目并在一次操作中执行所有删除操作。

Old: [1,2,3]旧: [1,2,3]

New: {“1”:1,”2”:2,”3”:3}新: {“1”:1,”2”:2,”3”:3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM