This guide walks you through creating a cluster and making your first connection to the DynamoDB-compatible feature of and .
Requirements
Before using the DynamoDB compatibility feature, ensure your cluster meets the following requirements:
Database proxy version: 2.3.63.1 or later.
Go to the PolarDB console and check your cluster's version on the page. If the version does not meet the requirements, .
Enable the DynamoDB-compatible feature
You can enable the DynamoDB-compatible feature for a cluster in one of the following two ways.
Existing cluster
If your cluster meets the Requirements, navigate to the Basic Information page of the cluster. Find the DynamoDB Compatibility setting and click On.
New cluster
If your cluster does not meet the Requirements or you want to use the current feature in a new cluster, you can create a new cluster in the PolarDB console.
Go to the custom purchase page for PolarDB clusters.
Set the to , and select the DynamoDB Compatibility checkbox.
Configure other options such as region, zone, and node specifications.
Create a dedicated DynamoDB account
Create a dedicated DynamoDB account to obtain the credentials (AccessKey) for API access.
On the page of your cluster, click Create Account.
Set Account Type to DynamoDB Account, and then set an account name and password.
NoteThis password is for managing the account in the console only, not for API access.
For example, set the account name to
dynamodb_user. The account name must start with a letter, end with a letter or digit, contain only lowercase letters, digits, and underscores (_), and not exceed 16 characters. The password must be 8 to 32 characters long and include at least three of the following character types: uppercase letters, lowercase letters, digits, and special characters.After the account is created, find it in the account list. The account name is the
Access Key ID. To obtain theSecretAccess Key, click View in the Key column.
Configure a DynamoDB endpoint
After you enable the DynamoDB-compatible feature, the system automatically creates a default DynamoDB endpoint. You can also create a custom endpoint.
On the Basic Information page of the cluster, find the default DynamoDB created by the system in the Database Connections section.
The card for this DynamoDB Endpoint shows the mode as Read/Write Splitting and includes the private connection endpoint and EndpointId. You can manage it by using the Release and Configure links.
(Optional) Click Create Custom Cluster Endpoint and set the endpoint type to DynamoDB. You can then specify the nodes to attach and preset the data consistency level for this endpoint.
NoteAfter the consistency level is set on a custom endpoint, all read requests to this endpoint adhere to this setting. You cannot override the preset consistency level by using the
ConsistentRead=trueparameter in a single API request.In this dialog box, you can also configure other parameters such as Read/Write Mode (for example, Read/Write Splitting), Endpoint Name, Load Balancing, Connection Pool, and Add New Nodes Automatically. After you complete the configuration, click OK.
Connection method and whitelist
Choose a connection method based on your server or client location.
Private connection (Recommended) If your application is deployed on Alibaba Cloud ECS, ensure that the ECS instance and the PolarDB cluster are in the same VPC. You also need to add the IP address or security group of the ECS instance to the cluster's .
Internet connection If you need to develop and test in a local environment, or if your ECS instance and PolarDB cluster are not in the same VPC, you can apply for an internet endpoint for the DynamoDB in the Database Connections section on the cluster's Basic Information page. You also need to add the IP address of your local environment or the public IP address of your ECS instance to the cluster's .
On the DynamoDB Endpoint card, click Apply for Public Endpoint next to the target endpoint. The system then generates a corresponding internet endpoint and port information.
NoteAccessing your cluster over the internet poses security risks. We recommend that you use an internet endpoint only for temporary development and testing. Release the internet endpoint when you are finished.
Connect and verify
Use the following Python code with the Boto3 SDK to verify your configuration. This example uses an ECS instance running the Alibaba Cloud Linux 3.2104 LTS 64-bit operating system.
Navigate to your project directory. This example uses
/home/testDynamoDB.mkdir /home/testDynamoDB cd /home/testDynamoDBIn the
/home/testDynamoDBdirectory, create avirtual environment(venv) to isolate project dependencies and prevent conflicts with global packages.python3 -m venv myenvActivate the virtual environment.
source myenv/bin/activateInstall the required Python dependency.
pip3 install boto3Create a Python file and copy the following code into it. Replace
endpoint_url,aws_access_key_id, andaws_secret_access_keywith the endpoint and DynamoDB Account credentials for your PolarDB cluster.vim main.pyimport boto3 from botocore.exceptions import ClientError # 1. Configure your connection details # The endpoint for your PolarDB cluster's DynamoDB-compatible feature. endpoint_url = "http://<your-polardb-ddb-endpoint>:<port>" # The Access Key ID from your DynamoDB account. aws_access_key_id = "<your-access-key-id>" # The Secret Access Key from your DynamoDB account. aws_secret_access_key = "<your-secret-access-key>" # For the DynamoDB-compatible feature of PolarDB, region_name must be set to "public". region_name = "public" # 2. Create a DynamoDB resource client dynamodb = boto3.resource( 'dynamodb', endpoint_url=endpoint_url, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name, ) table_name = 'usertable' # 3. Define functions for database operations def create_table(): """Creates the table, or gets it if it already exists.""" try: table = dynamodb.create_table( TableName=table_name, KeySchema=[{'AttributeName': 'userid', 'KeyType': 'HASH'}], # Partition key AttributeDefinitions=[{'AttributeName': 'userid', 'AttributeType': 'S'}] # ProvisionedThroughput is optional and ignored by PolarDB. ) print("Creating table... Waiting for it to become active.") table.meta.client.get_waiter('table_exists').wait(TableName=table_name) print("Table is active!") return table except ClientError as e: if e.response['Error']['Code'] == 'ResourceInUseException': print("Table already exists.") return dynamodb.Table(table_name) else: raise def put_items(table): """Puts a few items into the table.""" users = [ {'userid': 'user01', 'name': 'Alice', 'age': 24}, {'userid': 'user02', 'name': 'Bob', 'age': 30}, {'userid': 'user03', 'name': 'Charlie', 'age': 28} ] for user in users: table.put_item(Item=user) print("Inserted 3 items.") def scan_table(table): """Scans and prints all items in the table.""" response = table.scan() items = response.get('Items', []) print(f"Scanned {len(items)} items:") for item in items: print(item) def delete_table(table): """Deletes the table.""" table.delete() print("Deleting table... Waiting for it to be removed.") table.meta.client.get_waiter('table_not_exists').wait(TableName=table_name) print("Table deleted successfully.") # 4. Run the verification process if __name__ == '__main__': try: user_table = create_table() put_items(user_table) scan_table(user_table) finally: # Ensure the table is cleaned up even if errors occur. if 'user_table' in locals(): delete_table(user_table)After you run the script, you should see output similar to the following:
python3 main.pyCreating table... Waiting for it to become active. Table is active! Inserted 3 items. Scanned 3 items: {'age': Decimal('24'), 'name': 'Alice', 'userid': 'user01'} {'age': Decimal('30'), 'name': 'Bob', 'userid': 'user02'} {'age': Decimal('28'), 'name': 'Charlie', 'userid': 'user03'} Deleting table... Waiting for it to be removed. Table deleted successfully.This output confirms a successful connection and verifies your configuration.