2

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a cheaper way to do this than to pay the full cost of retrieving the item?
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.