如何从 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
                )

如果你把你的列表变成地图,你就可以根据地图键删除项目,一次操作完成所有删除。

旧:[1,2,3]

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

您可以 remove multiple items 通过单个操作从列表中使用 REMOVE myList[0], myList[2] 等更新表达式。这是使用 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)