Check unique hash_key in dynamodb - python

10,782

Solution 1

Rather than doing a query operation, you should just attempt to retrieve the item using get_item. If it exists, the item will be returned. If not, the call will raise a DynamoDBKeyNotFoundError which you can catch. So, something like:

def exists(hash_key):
    try:
        item = self.table.get_item(hash_key=<hash key>...)
    except boto.dynamodb.exceptions.DynamoDBKeyNotFoundError:
        item = None
    return item

would return None if the hash didn't exist and would return the item if it did exist.

Solution 2

Just ended up on this page after a google search. Here's a 2020 update:

The API behaviour has changed and is returning either 'the item' or 'nothing', but won't raise an exception: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.get_item

Here is an example of how to use get_item to query for a single item: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html#getting-an-item

And this SOF answer addresses the specific problem of checking for the existence of an item in a DDB table: https://stackoverflow.com/a/48589589/512155

Share:
10,782
zebra
Author by

zebra

Updated on June 13, 2022

Comments

  • zebra
    zebra almost 2 years

    i'm trying to check existence of an hash_key in dynamodb with boto (i can not update my filed if exist) i've try with query

       for i in self.table.query(hask_key=[value]):
          print i['url']
    

    But i miss an argument (???). I've try with scan but i need to check my hash_key, not attributes.

    I've try with get_item but i cannot manage the response if hash_key does not exist.

    Any advice?

    I've play with redis and it have exist method.

  • jocull
    jocull almost 3 years
    Is there a cheaper way to do this than to pay the full cost of retrieving the item?