How to check if DynamoDB table exists?

boto3 dynamodb check if item exists
dynamodb create if not exists
dynamodb describe-table
dynamodb list tables
dynamodb createtable
cannot create preexisting table
dynamodb create table
boto3 dynamodb backup

I'm a new user in boto3 and i'm using DynamoDB.

I went through over the DynamoDB api and I couldn't find any method which tell me if a table is already exists.

What is the best approach dealing this issue?

Should I try to create a new table and wrap it using try catch ?

From reading the documentation, I can see that there are three methods by which you can check if a table exists.

  1. The CreateTable API throws an error ResourceInUseException if the table already exists. Wrap the create_table method with try except to catch this
  2. You can use the ListTables API to get the list of table names associated with the current account and endpoint. Check if the table name is present in the list of table names you get in the response.
  3. The DescribeTable API will throw an error ResourceNotFoundException if the table name you request doesn't exist.

To me, the first option sounds better if you just want to create a table.

Edit: I see that some people are finding it difficult to catch the exceptions. I will put some code below for you to know how to handle exceptions in boto3.

Example 1

import boto3

dynamodb_client = boto3.client('dynamodb')

try:
    response = dynamodb_client.create_table(
        AttributeDefinitions=[
            {
                'AttributeName': 'Artist',
                'AttributeType': 'S',
            },
            {
                'AttributeName': 'SongTitle',
                'AttributeType': 'S',
            },
        ],
        KeySchema=[
            {
                'AttributeName': 'Artist',
                'KeyType': 'HASH',
            },
            {
                'AttributeName': 'SongTitle',
                'KeyType': 'RANGE',
            },
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5,
        },
        TableName='test',
    )
except dynamodb_client.exceptions.ResourceInUseException:
    # do something here as you require
    pass

Example 2

import boto3

dynamodb_client = boto3.client('dynamodb')


table_name = 'test'
existing_tables = dynamodb_client.list_tables()['TableNames']

if table_name not in existing_tables:
    response = dynamodb_client.create_table(
        AttributeDefinitions=[
            {
                'AttributeName': 'Artist',
                'AttributeType': 'S',
            },
            {
                'AttributeName': 'SongTitle',
                'AttributeType': 'S',
            },
        ],
        KeySchema=[
            {
                'AttributeName': 'Artist',
                'KeyType': 'HASH',
            },
            {
                'AttributeName': 'SongTitle',
                'KeyType': 'RANGE',
            },
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5,
        },
        TableName=table_name,
    )

Example 3

import boto3

dynamodb_client = boto3.client('dynamodb')

try:
    response = dynamodb_client.describe_table(TableName='test')
except dynamodb_client.exceptions.ResourceNotFoundException:
    # do something here as you require
    pass

What is the best way to check if table exists in DynamoDB?, use Aws\DynamoDb\Exception\ResourceNotFoundException; // <-- make sure this line is at the top public function TableExists($tableName)  aws dynamodb wait table-exists \ --table-name MusicCollection This command produces no output. For more information, see Basic Operations for Tables in the Amazon DynamoDB Developer Guide .

import boto3

from botocore.exceptions import ClientError

TABLE_NAME = "myTableName"
dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

table = dynamodb.Table(TABLE_NAME)

try:
    response = client.describe_table(TableName=TABLE_NAME)

except ClientError as ce:
if ce.response['Error']['Code'] == 'ResourceNotFoundException':
    print "Table " + TABLE_NAME + " does not exist. Create the table first and try again."
else:
    print "Unknown exception occurred while querying for the " + TABLE_NAME + " table. Printing full error:"
    pprint.pprint(ce.response)

table-exists, For more information see the AWS CLI version 2 installation instructions and migration guide. [ aws . dynamodb . wait ]. table-exists¶. Description¶. Wait until  What is the best way to check if table exists in DynamoDb? I would appreciate it if the code would be in PHP. 31827/what-is-the-best-way-to-check-if-table-exists-in-dynamodb

Check if DynamoDB table already exists and create one if it doesn't , Check if DynamoDB table already exists and create one if it doesn't. createTable.​py. import boto3. class tableCreate(object):. def __init__(self, **kwargs):. self. Is there a way to check if an item exists in a DynamoDB Table without using Query or Scan and that won't cause an exception. Using .Net Api. : aws. 1. Is there a way to check if an item exists in a DynamoDB Table without using Query or Scan and that won't cause an exception. Using .Net Api. 1.

You can use .table_status attr of any boto3 Table instance object. It returns it's status if exists (CREATING, UPDATING, DELETING, ACTIVE) or throws exception botocore.exceptions.ClientError: Requested resource not found: Table: <YOUR_TABLE_NAME> not found. You can wrap those conditions into try / except to have full info on the current table state.

import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('your_table_name_str')

try:
  is_table_existing = table.table_status in ("CREATING", "UPDATING",
                                             "DELETING", "ACTIVE")
except ClientError:
  is_table_existing = False
  print "Table %s doesn't exist." % table.name

How to check if DynamoDB table exists? – Icetutor, From reading the documentation, I can see that there are three methods by which you can check if a table exists. The CreateTable API throws  I just started out with Node.js and AWS DynamoDB and I'm stuck with a very basic problem I believe. I'm looking for a way to return a boolean if a particular key exists in a table. So here's the c

Alternate approach if you do not want to use boto3.client but only boto3.resource:

import boto3

database = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")    

table_name  = 'MyTable'
table_names = [table.name for table in database.tables.all()]

if table_name in table_names:
    print('table', table_name, 'exists')

Check table exist in dynamodb from AWS Lambda, The following method will check the table exist in dynamodb public boolean isTableExist(String tableName) { try { TableDescription  The CreateTable API throws an error ResourceInUseException if the table already exists. Wrap the create_table method with try except to catch this You can use the ListTables API to get the list of table names associated with the current account and endpoint. Check if the table name is present in the list of table names you get in the response.

Check table exist in dynamodb from AWS Lambda, The following method will check the table exist in dynamodb. “Check if (err) { status="false"; console.log(err, err.stack); // an error occurred } Check the backed up table > Restore Type the same name for the table as before, as the new table name. Restore table Restored database takes some time appear so wait for perhaps five minutes or may be longer.

Programmatically check table exist in AWS Dynamo DB from , Programmatically check table exist in AWS Dynamo DB from Lambda function. Tagged with serverless, java. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

How to check if DynamoDB table exists?, I went through over the DynamoDB api and I couldn't find any method which tell me if a table is already exists. What is the best approach  How to check if particular attribute exists in dynamodb? I.e I have file like geo.ip in dynamodb how to check if geo.ip exists in dynamodb? Can anybody tell what is the correct to check using aws cli?

Comments
  • use dynamodb-data-mapper check provides function ensureTableExists, to create table if not exists
  • With describe_table I get AttributeError: 'dynamodb.ServiceResource' object has no attribute 'describe_table'.
  • That is because you're using service resource instead of client. Check this line in your code: dynamodb_client = boto3.client('dynamodb')
  • Example 3 is great, but I was getting a ClientError thrown: ``` dynamodb = boto3.resource(self._dynamodb_resource_name, region_name=self._region, endpoint_url=self._endpoint_url) # Try removing the table and ignore if it does not exist table = dynamodb.Table(self._tableName) try: table.delete() except ClientError as e: if e.response['Error']['Code'] != 'ResourceNotFoundException': raise e ```
  • The code doesn't look like what I had posted above. Where did you get the code from? Is it working for you and where is ClientError imported from?
  • Thank you for this! I was losing what was left of my hair.
  • I like your code but can't figure out how to import the botocore.errorfactory.ResourceNotFoundException. I keep getting AttributeError: 'module' object has no attribute 'ResourceNotFoundException'. I'm imported boto3 and botocore.
  • @anon58192932 did you figure out how to import that exception? I'm facing the same issue.
  • @Phito sorry for the delay I just got back into work. Please see my answer that I'll be posting on how to check for the exception. It can't be imported directly as far as I understand.
  • @Phito: I have edited my answer to include example codes on how to catch exceptions in boto3.
  • @anupsabraham I didn't find the exact syntax to catch the exception so posting an example here _cwevents_client: BaseClient = _master_session.client('events', region_name=aws_region) try: _cwevents_client.describe_rule(Name=ruleName) logger.info("Determined that guarddutyAlert rule already exists") except _cwevents_client.exceptions.ResourceNotFoundException: logger.info("Creating the guarddutyAlert CloudWatch rule")