Boto DynamoDB2 conditional put_item

可紊 提交于 2019-12-06 04:35:53

问题


I am trying to have put_item to check if there is item with the same HashKey before actually adding the new item.

According to boto DynamoDB2 document, it is possible to do it with "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?

Thanks to all in advance.


回答1:


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. Note that you need to give a value if you want to go with 'Exists': True instead of 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




回答2:


Note that the parameter expected of put_item is now deprecated:

Parameters: expected (map)

There is a newer parameter available. Use ConditionExpression instead.

Use condition_expression instead:

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, e.g:

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.



来源:https://stackoverflow.com/questions/18117561/boto-dynamodb2-conditional-put-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!