Boto DynamoDB2条件put_item

时间:2013-08-08 03:48:58

标签: python conditional boto put

我试图让put_item在实际添加新项目之前检查是否存在具有相同HashKey的项目。

根据boto DynamoDB2文档,可以使用“Conditional Put”来完成。

我尝试了以下命令,但没有运气。

connection.put_item('table',item={'locationId':'a1', 'timestamp': time.time()}, expected={'locationID':False})

错误信息如下。

boto.exception.JSONResponseError: JSONResponseError: 400 Bad Request
{u'Message': u'Expected null', u'__type': u'com.amazon.coral.service#SerializationException'}

有没有人有DynamoDBv2的条件放?

提前感谢所有人。

2 个答案:

答案 0 :(得分:7)

您需要像这样编写它才能使语法正常工作。在任何地方都没有记录这是非常糟糕的。我只是遇到了完全相同的问题,并且在挖掘Java SDK文档时必须尝试50种不同的东西才能工作。请注意,如果您想使用'Exists': True代替False,则需要提供值。

connection.put_item(
    'table',
    item={
        'locationId':{'S': 'a1'},
        'timestamp': {'N': str(time.time())
    },
    expected={
        'locationID': {'Exists': False}
    }
    #expected={
    #    'locationID': {'Exists': True, 'Value': {'N': '0'}}
    #}
)

希望它有所帮助!

修改:the question that helped me with the syntax enough to make it workcode in the boto integration tests

答案 1 :(得分:1)

请注意,expected的参数put_item现为deprecated

  

参数:expected(map)

     

有一个更新的参数可用。请改用ConditionExpression。

改为使用condition_expression

connection.put_item(
    'table',
    item={
        'locationId': {'S': 'a1'}, 
        'timestamp': {'S': str(time.time())}
    },
    condition_expression='attribute_exists(locationId)'
)

也可以链接表达式和使用命名参数,例如:

connection.put_item(
    'table',
    item={
        'locationId': {'S': 'a1'}, 
        'timestamp': {'S': str(time.time())}
    },
    condition_expression=(
        'attribute_exists(locationId) AND '
        'NOT attribute_type(locationId, :expected_type)'
    ),
    expression_attribute_values={
        ':expected_type': {'S': 'NULL'}  # String parameter of value 'NULL'
    }
)

See Performing Conditional Writes with Condition Expressions for more details