This topic describes how to connect to a DynamoDB-compatible instance using the AWS CLI, Python, and Java.
Prerequisites
A DynamoDB-compatible instance is required. When you create the instance, select DynamoDB as the protocol type. For more information, see Create a sharded cluster instance.
Connection endpoint
Obtain the connection endpoint for your DynamoDB-compatible instance.
-
Log on to the ApsaraDB for MongoDB console.
-
In the upper-left corner of the page, select the resource group and region of the instance.
-
In the left-side navigation pane, click List of Shard cluster instances.
-
Find the target instance and click its ID.
-
In the left-side navigation pane, click Database Connection.
-
In the VPC Connection section, view the connection endpoint of the instance. The Protocol Type for this endpoint is DynamoDB-compatible protocol, and the address starts with
dds-.
If your application is deployed on an ECS instance, your ApsaraDB for MongoDB instance and the ECS instance must meet the following conditions to ensure network connectivity.
-
They must be in the same region. If you have an existing ECS instance, you can check its region. For more information, see View the region of an ECS instance.
-
Optional: For lower network latency, we recommend placing them in the same zone. If you have an existing ECS instance, you can check its zone. For more information, see View the zone of an ECS instance.
-
They must use the same network type. If you have an existing ECS instance, you can check its network type. For more information, see View the network type of an ECS instance. If the ECS instance uses the Classic network, you can migrate it from the Classic network to a VPC. For more information, see Migrate an ECS instance from the classic network to a VPC.
Connect using AWS CLI
This section shows how to use the AWS Command Line Interface (AWS CLI) on an Ubuntu 16.04.6 LTS system to connect to a DynamoDB-compatible instance. For more information about the AWS CLI, see What Is the AWS Command Line Interface?.
-
Install the AWS CLI client.
-
Run the following command to download the latest version of the AWS CLI and save it as
awscliv2.zip:curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" -
Run the following command to unzip the
awscliv2.zipfile:unzip awscliv2.zipNoteIf you do not have
unzipinstalled, run thesudo apt install unzipcommand to install it. -
Run the following command to install the AWS CLI:
sudo ./aws/install
When the message
You can now run: /usr/local/bin/aws --versionappears, the AWS CLI is installed. You can then run the/usr/local/bin/aws --versioncommand to check the current version of the AWS CLI. -
-
Run the
/usr/local/bin/aws configurecommand to configure the AWS CLI. Enter the following values, pressing Enter after each one.Parameter
Description
Example
AWS Access Key IDEnter an access key ID. The DynamoDB-compatible service does not validate this key, so you can enter any string of characters.
XXXXXXXXXXAWS Secret Access KeyEnter a secret access key. The DynamoDB-compatible service does not validate this key, so you can enter any string of characters.
XXXXXXXXXXDefault region nameEnter a default AWS region name.
us-west-2Default output formatThe default output format. You can leave this parameter blank.
jsonNoteFor more information about how to configure the AWS CLI, see Configuration basics.
-
Run the following command to connect to the target DynamoDB-compatible instance and create a table.
aws dynamodb --endpoint-url <connection-endpoint-of-your-DynamoDB-compatible-instance> \ create-table --table-name <your-table-name> \ --attribute-definitions AttributeName=<attribute-name>,AttributeType=<attribute-data-type> \ --key-schema AttributeName=<primary-key-attribute-name>,KeyType=<key-role> \ --provisioned-throughput ReadCapacityUnits=<provisioned-read-throughput>,WriteCapacityUnits=<provisioned-write-throughput>Parameter
Description
--endpoint-urlThe endpoint of the target DynamoDB-compatible instance. The endpoint must start with
http://.create-tableThe command to create a table.
NoteFor more information, see create-table.
--table-nameThe name of the table to create.
--attribute-definitionsAn array of attributes that describe the key schema for the table or index. This parameter requires the following sub-parameters:
-
AttributeName: The name of the attribute. -
AttributeType: The data type of the attribute.NoteFor more information, see create-table.
--key-schemaThe attributes that make up the primary key for a table or index. This parameter requires the following sub-parameters:
-
AttributeName: The name of a key attribute. The attribute is defined by using the--attribute-definitionsparameter. -
KeyType: The role of the key. Valid values: HASH and RANGE. HASH specifies the partition key and RANGE specifies the sort key.NoteFor more information, see create-table.
--provisioned-throughputThe provisioned throughput settings for the table or index. This parameter requires the following sub-parameters:
-
ReadCapacityUnits: The provisioned read throughput. -
WriteCapacityUnits: The provisioned write throughput.
NoteFor more information, see create-table.
Example:
/usr/local/bin/aws dynamodb --endpoint-url http://dds-xxxx.mongodb.rds.aliyuncs.com:3717 \ # Connect to the specified endpoint of the DynamoDB-compatible instance. create-table --table-name student \ # Create a table named student. --attribute-definitions AttributeName=name,AttributeType=S AttributeName=age,AttributeType=N \ # The table schema includes a 'name' attribute of type String (S) and an 'age' attribute of type Number (N). --key-schema AttributeName=name,KeyType=HASH AttributeName=age,KeyType=RANGE \ # Specify 'name' as the partition key and 'age' as the sort key. --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 # Set the provisioned read throughput and provisioned write throughput to 5.If the following output is returned, you have connected to the target DynamoDB-compatible instance and created a table.
{ "TableDescription": { "TableName": "student", "KeySchema": [ { "AttributeName": "name", "KeyType": "HASH" }, { "AttributeName": "age", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "TableSizeBytes": 0, "ItemCount": 0 } } -
Connect using Python
-
Python 2.6 or a later version is installed. For more information, see the official Python website.
-
Boto3 is installed. For more information, see Installing Boto3.
The following code demonstrates how to connect to a DynamoDB-compatible instance using Python and create a table named Book:
import boto3
def create_book_table(dynamodb=None):
if not dynamodb:
# Replace the endpoint_url with the actual endpoint of your DynamoDB-compatible instance.
dynamodb = boto3.resource('dynamodb', endpoint_url="http://dds-xxxx.mongodb.rds.aliyuncs.com:3717")
table = dynamodb.create_table(
TableName='Book',
KeySchema=[
{
'AttributeName':'title',
'KeyType':'HASH'
},
{
'AttributeName':'year',
'KeyType':'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName':'title',
'AttributeType':'S'
},
{
'AttributeName':'year',
'AttributeType':'N'
},
],
ProvisionedThroughput={
'ReadCapacityUnits':5,
'WriteCapacityUnits':5
}
)
return table
if __name__ == '__main__':
book_table =create_book_table()
print("Table status:", book_table.table_status)
Connect using Java
The AWS SDK for Java is required. For more information, see Set up the AWS SDK for Java.
The following code demonstrates how to use Java to connect to a DynamoDB-compatible instance and create a table named Book:
package com.amazonaws.codesamples.gsg;
import java.util.Arrays;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
public class MoviesCreateTable {
public static void main(String[] args) throws Exception {
// Replace the endpoint and region with the actual values for your DynamoDB-compatible instance.
AmazonDynamoDB client =AmazonDynamoDBClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://dds-xxxx.mongodb.rds.aliyuncs.com:3717",
"us-east-1"))
.build();
DynamoDB dynamoDB = new DynamoDB(client);
String tableName ="Book";
try {
System.out.println("Creating table...");
Table table =dynamoDB.createTable(tableName,
Arrays.asList(new
KeySchemaElement("title", KeyType.HASH), // partition key
new KeySchemaElement("year", KeyType.RANGE)), // sort key
Arrays.asList(new AttributeDefinition("title", ScalarAttributeType.S),
new AttributeDefinition("year", ScalarAttributeType.N)),
new ProvisionedThroughput(5L, 5L));
table.waitForActive();
System.out.println("OK. Table status: " + table.getDescription().getTableStatus());
}
catch (Exception e) {
System.err.println("Unable to create table: ");
System.err.println(e.getMessage());
}
}
}
Connection examples in other languages
For more examples, see Getting started with DynamoDB and the AWS SDKs.