简体   繁体   English

Boto DynamoDB2条件put_item

[英]Boto DynamoDB2 conditional put_item

I am trying to have put_item to check if there is item with the same HashKey before actually adding the new item. 我想在实际添加新项目之前让put_item检查是否存在具有相同HashKey的项目。

According to boto DynamoDB2 document, it is possible to do it with "Conditional Put". 根据boto DynamoDB2文档,可以使用“Conditional Put”进行操作。

I tried following command but no luck. 我尝试了以下命令,但没有运气。

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

The error message is as following. 错误消息如下。

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

Does anyone have a conditional put with DynamoDBv2? 有没有人有DynamoDBv2的条件放?

Thanks to all in advance. 感谢所有提前。

You need to write it like this for the syntax to work. 您需要像这样编写它才能使语法正常工作。 It's extremely bad that this isn't documented anywhere. 在任何地方都没有记录这是非常糟糕的。 I just had the exact same problem and had to try 50 different things while digging through the Java SDK documentation for it to work. 我只是遇到了完全相同的问题,并且在挖掘Java SDK文档时必须尝试50种不同的东西才能工作。 Note that you need to give a value if you want to go with 'Exists': True instead of False . 请注意,如果要使用'Exists': True ,则需要提供值'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'}}
    #}
)

Hope it helps! 希望能帮助到你!

Edit: the question that helped me with the syntax enough to make it work and code in the boto integration tests 编辑: 帮助我使用语法足以使其 在boto集成测试中 工作编码的问题

Note that the parameter expected of put_item is now deprecated : 请注意, put_item expected参数现已弃用

Parameters: expected (map) 参数:预期(地图)

There is a newer parameter available. 有一个更新的参数可用。 Use ConditionExpression instead. 请改用ConditionExpression。

Use condition_expression instead: 改为使用condition_expression

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

It's also possible to chain expressions and to use named parameters, eg: 也可以链接表达式并使用命名参数,例如:

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 . 有关更多详细信息,请参阅使用条件表达式执行条件写入

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

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