5

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.

4

2 回答 2

7

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

于 2013-10-01T13:23:30.073 回答
1

请注意,参数expectedofput_item现在已弃用

参数:预期(地图)

有一个更新的参数可用。请改用 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'
    }
)

有关详细信息,请参阅使用条件表达式执行条件写入

于 2017-02-01T11:57:51.423 回答