全部產品
Search
文件中心

PolarDB:使用說明

更新時間:Jan 27, 2026

本文將引導您完成從建立叢集到首次成功訪問的全過程,協助您快速上手使用PolarDB PostgreSQL版的DynamoDB相容功能。

前提條件

在使用DynamoDB相容能力前,請確保您的叢集版本滿足以下要求:

  • 核心版本PostgreSQL 14,且修訂版本需為2.0.14.17.35.0及以上。

  • 資料庫代理版本:需為2.3.59及以上。

  • PolarDB PostgreSQL分布式版與Serverless叢集暫不支援DynamoDB相容能力。

說明

您可前往PolarDB控制台,在叢集的配置與管理 > 版本管理頁面中查看對應的版本。若版本不滿足要求,請升級對應的小版本

開啟相容DynamoDB能力

您可以通過以下兩種方式為叢集開啟DynamoDB相容功能。

已有叢集

若您的叢集滿足前提條件,則可以在叢集的基本信息頁面中,找到DynamoDB兼容能力配置項,單擊开启image

建立新叢集

若您的叢集不滿足前提條件或希望在新的叢集中使用當前功能,則可以在PolarDB控制台上建立一個新的叢集。

  1. 前往PolarDB叢集自訂購買頁面

  2. 將資料庫引擎設定為PostgreSQL 14,並勾選DynamoDB相容能力

  3. 根據業務需求配置地區、可用性區域和節點規格等其他選項。

image

建立DynamoDB專用帳號

您需要建立一個專用的DynamoDB帳號來擷取用於API訪問的身份憑證(AccessKey)。

  1. 在叢集的配置与管理 > 账号管理頁面,單擊创建账号

  2. 將帳號類型選擇為DynamoDB账号,並設定帳號名和密碼。

    說明

    此處設定的密碼僅用於在控制台管理該帳號,並非API訪問所用的密鑰。

    image

  3. 建立成功後,在帳號列表中找到該帳號。帳號名即為Access Key ID,單擊密鑰列的查看即可擷取SecretAccess Key

    image

配置DynamoDB訪問地址

開啟DynamoDB相容功能後,系統會自動建立一個預設的DynamoDB訪問地址。您也可以建立自訂地址以滿足特定需求。

  • 在叢集基本信息頁面的数据库连接地區,可以找到系統預設建立的DynamoDB地址

    image

  • (可選)單擊创建自定义地址並選擇地址類型為DynamoDB地址,可以為該地址指定掛載的節點並預設資料一致性層級。

    說明

    一致性層級在自訂地址上設定後,該地址下的所有讀請求都將遵循此設定。當前不支援在單次API請求中通過ConsistentRead=true參數來覆蓋地址上預設的一致性層級。

    image

選擇串連方式與設定叢集白名單

根據您的伺服器或用戶端位置,選擇合適的網路連接方式。

  • 私網串連(推薦) 如果您的應用程式部署在阿里雲ECS上,請確保ECS與PolarDB叢集位於同一VPC內,並將ECS的IP地址或安全性群組添加到叢集的白名單中。

  • 公網串連 如需在本地環境進行開發與測試,或當ECS與PolarDB叢集不位於同一VPC內時,您可以在叢集基本信息頁面的数据库连接地區,為DynamoDB地址申請一個公網地址。並將本地環境IP地址或ECS公網IP地址添加到叢集的白名單中。

    說明

    公網地址訪問會增加安全風險。建議僅用於臨時開發測試,完成後請及時釋放公網地址。

    image

串連並驗證

使用以下Python範例程式碼,通過Boto3 SDK驗證您的配置是否正確。以下內容以ECS執行個體,Alibaba Cloud Linux 3.2104 LTS 64位作業系統為例進行說明。

  1. 根據實際業務需求,進入指定的專案目錄。此處以/home/testDynamoDB為例。

    mkdir /home/testDynamoDB
    cd /home/testDynamoDB
  2. /home/testDynamoDB目錄中,建立虛擬環境(venv)隔離專案依賴,避免全域汙染。

    python3 -m venv myenv
  3. 啟用虛擬環境

    source myenv/bin/activate
  4. 安裝所需的Python依賴庫。

    pip3 install boto3
  5. 建立一個Python檔案,並複製以下代碼。請將endpoint_urlaws_access_key_id以及aws_secret_access_key替換為PolarDB叢集的串連地址DynamoDB帳號

    vim main.py
    import boto3
    from botocore.exceptions import ClientError
    
    # 1. Configure your connection details
    # Endpoint URL from Step 2
    endpoint_url = "http://<your-polardb-ddb-endpoint>:<port>"
    # Access Key ID from Step 3
    aws_access_key_id = "<your-access-key-id>"
    # Secret Access Key from Step 3
    aws_secret_access_key = "<your-secret-access-key>"
    # For PolarDB-DDB, region_name should be 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)
  6. 執行該指令碼後,您應該會看到類似以下的輸出:

    python3 main.py
    Creating 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.

    看到以上輸出,表明您已成功串連並操作資料庫,所有配置均已生效。