boto DynamoDB:如何防止用 batch_write 覆盖项目?

boto DynamoDB: How can I prevent overwriting items with batch_write?

我正在使用 boto's DynamoDB v2 并且正在将项目批量写入 table。但是我无法阻止 DynamoDB 覆盖现有项目的属性。我宁愿让进程失败。

table 具有以下架构:

from boto.dynamodb2.table import Table, HashKey, RangeKey

conn = get_connection()
t = Table.create(
        'intervals',
        schema=[
            HashKey('id'),
            RangeKey('start')
        ],
        connection=conn
    )

假设我插入一项:

item = {
    'id': '4920',
    'start': '20',
    'stop': '40'
}
t.put_item(data=item)

现在,当我使用 batch_write 插入新项目时,我想确保 DynamoDB 不会覆盖现有项目。根据 the documentation,这应该通过 BatchTable class 的 put_item 方法中的 overwrite 参数来实现(这是用作上下文的那个下例中的经理)

new_items = [{
    'id': '4920',
    'start': '20',
    'stop': '90'
}]

with t.batch_write() as batch:
    for i in new_items:
        batch.put_item(data=i, overwrite=False)

然而,事实并非如此。我示例中的 stop 属性获得新值 90。所以之前的值(40)被覆盖了。

如果我使用 table 自己的 put_item 方法,则 overwrite 参数有效。将其设置为 True 会替换 stop 值,而将其设置为 False 会导致 ConditionalCheckFailedException.

如何在使用 batch_write 时获得该异常?

我不认为有任何方法可以用 DynamoDB 做到这一点。批处理 API 不支持。 BatchTable对象的put_item方法接受overwrite参数是boto的一个bug。如果检查代码,您会发现它对该参数没有任何作用。它被忽略了,因为它无能为力。 DynamoDB 只是不支持这一点。至少现在还没有。