DynamoDB Start
DynamoDB is a fully managed NoSQL database service provided by Amazon. It requires only a primary key and doesn’t require a schema to create a table. It can store any amount of data and serve any amount of traffic. With DyanmoDB, you can expect a good performance even when it scales up. It is a very simple and small API that follows key-value method to store, access and perform advanced data retrieval.
DynamoDB comprises of three fundamental units known as table, attribute, and items. A table holds a set of items, an attribute is the simplest element that stores data without any further division and item holds a set of attributes.
DynamoDB use cases
- Financial service applications
- Gaming applications
- Streaming applications
Setting up DynamoDB
- web service
- downloadable version
Attribute Data Types
DynamoDB supports a large set of data types for table attributes. Each data type falls into one of the three following categories:
- Scalar − These types represent a single value, and include number, string, binary, Boolean, and null.
- Document − These types represent a complex structure possessing nested attributes, and include lists and maps.
- Set − These types represent multiple scalars, and include string sets, number sets, and binary sets.
Partitions
Amazon DynamoDB stores data in partitions. A partition is an allocation of storage for a table, backed by solid state drives (SSDs) and automatically replicated across multiple Availability Zones within an AWS Region. Partition management is handled entirely by DynamoDB—you never have to manage partitions yourself.
When you create a table, the initial status of the table is CREATING. During this phase, DynamoDB allocates sufficient partitions to the table so that it can handle your provisioned throughput requirements. You can begin writing and reading table data after the table status changes to ACTIVE.
Table, Items, Attributes, Keys, Indexes
- A table can be visualized as a group of items. Taking an example of Employee records, you will have Employee Name, Employee ID, Address and Phone Number all such items will be stored in a table.
- An item is a set of attributes in a table. You can also understand an item as a set of attributes that can uniquely define your entry in a table. For example, an item in Employee records will identify a single employee.
- An attribute is a single field that is attached to an item. E.g. Employee Name.
- Primary Keys
- Partition key: This is a simple primary key. If the table has only a partition key, then no two items can have the same partition key value. The primary key must be unique for each item in the table irrespective of the type of primary key that you choose.
- Composite primary key: This is a combination of partition key and sort key. If the table has a composite primary key, then two items might have the same partition key value. However, those items must have different sort key values.
- Indexes
- DynamoDB attributes
- In Amazon DynamoDB, an item is a collection of attributes. Each attribute has a name and a value. An attribute value can be a scalar, a set, or a document type. For more information, see Amazon DynamoDB: How it works. DynamoDB provides four operations for basic create, read, update, and delete (CRUD) functionality.
- Working with items and attributes.
DynamoDB Streams
- Working with streams
- Kinesis Data Streams
- You can use Amazon Kinesis Data Streams to capture changes to Amazon DynamoDB.
- DynamoDB Streams
- Kinesis Data Streams
PartiQL statements for DynamoDB
PartiQL Statements
Amazon DynamoDB supports the following PartiQL statements.
DynamoDB does not support all PartiQL statements.
This reference provides basic syntax and usage examples of PartiQL statements that you manually run using the AWS CLI or APIs.
Data manipulation language (DML) is the set of PartiQL statements that you use to manage data in DynamoDB tables. You use DML statements to add, modify, or delete data in a table.
The following DML and query language statements are supported:
- PartiQL select statements for DynamoDB
- PartiQL update statements for DynamoDB
- PartiQL insert statements for DynamoDB
- PartiQL delete statements for DynamoDB
Basic operations on DynamoDB tables
- Create a table
- Write data to a table
- Read data from a table
- Update data in a table
- Delete table
- Query data in a table
1. LocalStack
awslocal configure (sample)
Run:
awslocal configure
AWS Access Key ID [****************test]:
AWS Secret Access Key [****************test]:
Default region name [test]:
Default output format [json]:
2. dynamodb-admin
Get started with the AWS SDK for Java 2.x
Create a table
- AWS Management Console
- AWS CLI
- AWS SDK
- LocalStack
AWS Management Console
To create a new Music table using the DynamoDB console:
- Sign in to the AWS Management Console and open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- In the left navigation pane, choose Tables.
- Choose Create table.
- Enter the Table details as follows:
- For Table name, enter Music.
- For Partition key, enter Artist.
- For Sort key, enter SongTitle.
- Once the table is in ACTIVE status, we recommend that you enable Point-in-time backups for DynamoDB on the table.
AWS CLI
The following AWS CLI example creates a new Music table using create-table (Linux).
aws dynamodb create-table \
--table-name Music \
--attribute-definitions \
AttributeName=Artist,AttributeType=S \
AttributeName=SongTitle,AttributeType=S \
--key-schema \
AttributeName=Artist,KeyType=HASH \
AttributeName=SongTitle,KeyType=RANGE \
--provisioned-throughput \
ReadCapacityUnits=5,WriteCapacityUnits=5 \
--table-class STANDARD
AWS SDK
The following code examples show how to create a DynamoDB table using an AWS SDK (Java).
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class CreateTable {
public static void main(String[] args) {
final String usage = """
Usage:
<tableName> <key>
Where:
tableName - The Amazon DynamoDB table to create (for example, Music3).
key - The key for the Amazon DynamoDB table (for example, Artist).
""";
if (args.length != 2) {
System.out.println(usage);
System.exit(1);
}
String tableName = args[0];
String key = args[1];
System.out.println("Creating an Amazon DynamoDB table " + tableName + " with a simple primary key: " + key);
Region region = Region.US_EAST_1;
DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();
String result = createTable(ddb, tableName, key);
System.out.println("New table is " + result);
ddb.close();
}
public static String createTable(DynamoDbClient ddb, String tableName, String key) {
DynamoDbWaiter dbWaiter = ddb.waiter();
CreateTableRequest request = CreateTableRequest.builder()
.attributeDefinitions(AttributeDefinition.builder()
.attributeName(key)
.attributeType(ScalarAttributeType.S)
.build())
.keySchema(KeySchemaElement.builder()
.attributeName(key)
.keyType(KeyType.HASH)
.build())
.provisionedThroughput(ProvisionedThroughput.builder()
.readCapacityUnits(10L)
.writeCapacityUnits(10L)
.build())
.tableName(tableName)
.build();
String newTable;
try {
CreateTableResponse response = ddb.createTable(request);
DescribeTableRequest tableRequest = DescribeTableRequest.builder()
.tableName(tableName)
.build();
// Wait until the Amazon DynamoDB table is created.
WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
waiterResponse.matched().response().ifPresent(System.out::println);
newTable = response.tableDescription().tableName();
return newTable;
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}
}
LocalStack
You can create a DynamoDB table using the CreateTable API. Execute the following command to create a table named Music with a primary key id:
awslocal dynamodb create-table \
--table-name Music \
--attribute-definitions \
AttributeName=Artist,AttributeType=S \
AttributeName=SongTitle,AttributeType=S \
--key-schema \
AttributeName=Artist,KeyType=HASH \
AttributeName=SongTitle,KeyType=RANGE \
--provisioned-throughput \
ReadCapacityUnits=5,WriteCapacityUnits=5 \
--table-class STANDARD
When
docker run -p 8000:8000 amazon/dynamodb-local
run
awslocal dynamodb create-table \
--endpoint-url http://localhost:8000 \
--table-name Music \
--attribute-definitions \
AttributeName=Artist,AttributeType=S \
AttributeName=SongTitle,AttributeType=S \
--key-schema \
AttributeName=Artist,KeyType=HASH \
AttributeName=SongTitle,KeyType=RANGE \
--provisioned-throughput \
ReadCapacityUnits=5,WriteCapacityUnits=5 \
--table-class STANDARD
list-tables:
awslocal dynamodb list-tables --region us-east-1
or
awslocal dynamodb list-tables \
--endpoint-url http://localhost:8000 \
--region us-east-1
{
"TableNames": [
"Music"
]
}
Write data to a table
In this step, you insert several items into the table that you created in: Create a table.
- AWS Management Console
- AWS CLI
- AWS SDK
- LocalStack
AWS Management Console
Follow these steps to write data to the Music table using the DynamoDB console.
- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- In the left navigation pane, choose Tables.
- On the Tables page, choose the Music table.
- Choose Explore table items.
- In the Items returned section, choose Create item.
- On the Create item page, do the following to add items to your table:
- Choose Add new attribute, and then choose Number.
- For Attribute name, enter Awards.
- Repeat this process to create an AlbumTitle of type String.
- Enter the following values for your item:
- For Artist, enter No One You Know.
- For SongTitle, enter Call Me Today.
- For AlbumTitle, enter Somewhat Famous.
- For Awards, enter 1.
- Choose Create item.
- Repeat this process and create another item with the following values:
- For Artist, enter Acme Band.
- For SongTitle enter Happy Day.
- For AlbumTitle, enter Songs About Life.
- For Awards, enter 10.
- Do this one more time to create another item with the same Artist as the previous step, but different values for the other attributes:
- For Artist, enter Acme Band.
- For SongTitle enter PartiQL Rocks. For AlbumTitle, enter Another Album Title. For Awards, enter 8.
AWS CLI
Linux
aws dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "1"}}'
aws dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Howdy"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "2"}}'
aws dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}, "AlbumTitle": {"S": "Songs About Life"}, "Awards": {"N": "10"}}'
aws dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "PartiQL Rocks"}, "AlbumTitle": {"S": "Another Album Title"}, "Awards": {"N": "8"}}'
AWS SDK
Puts an item into a table using DynamoDbClient.
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*
* To place items into an Amazon DynamoDB table using the AWS SDK for Java V2,
* its better practice to use the
* Enhanced Client. See the EnhancedPutItem example.
*/
public class PutItem {
public static void main(String[] args) {
final String usage = """
Usage:
<tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>
Where:
tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3).
key - The key used in the Amazon DynamoDB table (for example, Artist).
keyval - The key value that represents the item to get (for example, Famous Band).
albumTitle - The Album title (for example, AlbumTitle).
AlbumTitleValue - The name of the album (for example, Songs About Life ).
Awards - The awards column (for example, Awards).
AwardVal - The value of the awards (for example, 10).
SongTitle - The song title (for example, SongTitle).
SongTitleVal - The value of the song title (for example, Happy Day).
**Warning** This program will place an item that you specify into a table!
""";
if (args.length != 9) {
System.out.println(usage);
System.exit(1);
}
String tableName = args[0];
String key = args[1];
String keyVal = args[2];
String albumTitle = args[3];
String albumTitleValue = args[4];
String awards = args[5];
String awardVal = args[6];
String songTitle = args[7];
String songTitleVal = args[8];
Region region = Region.US_EAST_1;
DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();
putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle,
songTitleVal);
System.out.println("Done!");
ddb.close();
}
public static void putItemInTable(DynamoDbClient ddb,
String tableName,
String key,
String keyVal,
String albumTitle,
String albumTitleValue,
String awards,
String awardVal,
String songTitle,
String songTitleVal) {
HashMap<String, AttributeValue> itemValues = new HashMap<>();
itemValues.put(key, AttributeValue.builder().s(keyVal).build());
itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());
itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build());
itemValues.put(awards, AttributeValue.builder().s(awardVal).build());
PutItemRequest request = PutItemRequest.builder()
.tableName(tableName)
.item(itemValues)
.build();
try {
PutItemResponse response = ddb.putItem(request);
System.out.println(tableName + " was successfully updated. The request id is "
+ response.responseMetadata().requestId());
} catch (ResourceNotFoundException e) {
System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
System.err.println("Be sure that it exists and that you've typed its name correctly!");
System.exit(1);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}
LocalStack
You can insert an item into a DynamoDB table using the PutItem API. Execute the following command to insert an item into the Music table:
awslocal dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "1"}}'
awslocal dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Howdy"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "2"}}'
awslocal dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}, "AlbumTitle": {"S": "Songs About Life"}, "Awards": {"N": "10"}}'
awslocal dynamodb put-item \
--table-name Music \
--item \
'{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "PartiQL Rocks"}, "AlbumTitle": {"S": "Another Album Title"}, "Awards": {"N": "8"}}'
Read data from a table
In this step, you'll read back one of the items that you created in Write data to a table.
- AWS Management Console
- AWS CLI
- AWS SDK
- LocalStack
AWS Management Console
- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- In the left navigation pane, choose Tables.
- On the Tables page, choose the Music table.
- Choose Explore table items.
- On the Items returned section, view the list of items stored in the table, sorted by Artist and SongTitle. The first item in the list is the one with the Artist named Acme Band and the SongTitle PartiQL Rocks.
AWS CLI
The following AWS CLI example reads an item from the Music. You can do this either through the DynamoDB API or PartiQL, a SQL-compatible query language for DynamoDB.
- DynamoDB API
- PartiQL for DynamoDB
DynamoDB API
Linux
aws dynamodb get-item --consistent-read \
--table-name Music \
--key '{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}'
PartiQL for DynamoDB
Linux
aws dynamodb execute-statement --statement "SELECT * FROM Music \
WHERE Artist='Acme Band' AND SongTitle='Happy Day'"
AWS SDK
Java
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*
* To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2,
* its better practice to use the
* Enhanced Client, see the EnhancedGetItem example.
*/
public class GetItem {
public static void main(String[] args) {
final String usage = """
Usage:
<tableName> <key> <keyVal>
Where:
tableName - The Amazon DynamoDB table from which an item is retrieved (for example, Music3).\s
key - The key used in the Amazon DynamoDB table (for example, Artist).\s
keyval - The key value that represents the item to get (for example, Famous Band).
""";
if (args.length != 3) {
System.out.println(usage);
System.exit(1);
}
String tableName = args[0];
String key = args[1];
String keyVal = args[2];
System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName);
Region region = Region.US_EAST_1;
DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();
getDynamoDBItem(ddb, tableName, key, keyVal);
ddb.close();
}
public static void getDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) {
HashMap<String, AttributeValue> keyToGet = new HashMap<>();
keyToGet.put(key, AttributeValue.builder()
.s(keyVal)
.build());
GetItemRequest request = GetItemRequest.builder()
.key(keyToGet)
.tableName(tableName)
.build();
try {
// If there is no matching item, GetItem does not return any data.
Map<String, AttributeValue> returnedItem = ddb.getItem(request).item();
if (returnedItem.isEmpty())
System.out.format("No item found with the key %s!\n", key);
else {
Set<String> keys = returnedItem.keySet();
System.out.println("Amazon DynamoDB table attributes: \n");
for (String key1 : keys) {
System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString());
}
}
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}
LocalStack
- DynamoDB API
- PartiQL for DynamoDB
DynamoDB API
Linux
awslocal dynamodb get-item --consistent-read \
--table-name Music \
--key '{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}'Output:
{
"Item": {
"Artist": {
"S": "Acme Band"
},
"AlbumTitle": {
"S": "Songs About Life"
},
"Awards": {
"N": "10"
},
"SongTitle": {
"S": "Happy Day"
}
}
}
PartiQL for DynamoDB
Linux
awslocal dynamodb execute-statement --statement "SELECT * FROM Music \
WHERE Artist='Acme Band' AND SongTitle='Happy Day'"Output:
{
"Item": {
"Artist": {
"S": "Acme Band"
},
"AlbumTitle": {
"S": "Songs About Life"
},
"Awards": {
"N": "10"
},
"SongTitle": {
"S": "Happy Day"
}
}
}
Update data in a table
In this step, you update an item that you created in Write data to a table.
- AWS Management Console
- AWS CLI
- AWS SDK
- LocalStack
AWS Management Console
- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- In the left navigation pane, choose Tables.
- Choose the Music table from the table list.
- Choose Explore table items.
- In Items returned, for the item row with Acme Band Artist and Happy Day SongTitle, do the following:
- Place your cursor on the AlbumTitle named Songs About Life.
- Choose the Edit icon.
- In the Edit String popup window, enter Songs of Twilight.
- Choose Save.
infoAlternatively, to update an item, do the following in the Items returned section:
- Choose the item row with Artist named Acme Band and SongTitle named Happy Day.
- From the Actions dropdown list, choose Edit item.
- For enter AlbumTitle, enter Songs of Twilight.
- Choose Save and close.
AWS CLI
The following AWS CLI example reads an item from the Music. You can do this either through the DynamoDB API or PartiQL, a SQL-compatible query language for DynamoDB.
- DynamoDB API
- PartiQL for DynamoDB
DynamoDB API
Linux
aws dynamodb update-item \
--table-name Music \
--key '{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}' \
--update-expression "SET AlbumTitle = :newval" \
--expression-attribute-values '{":newval":{"S":"Updated Album Title"}}' \
--return-values ALL_NEW
PartiQL for DynamoDB
Linux
aws dynamodb execute-statement --statement "UPDATE Music \
SET AlbumTitle='Updated Album Title' \
WHERE Artist='Acme Band' AND SongTitle='Happy Day' \
RETURNING ALL NEW *"
AWS SDK
Java
/// <summary>
/// Updates an existing item in the movies table.
/// </summary>
/// <param name="client">An initialized Amazon DynamoDB client object.</param>
/// <param name="newMovie">A Movie object containing information for
/// the movie to update.</param>
/// <param name="newInfo">A MovieInfo object that contains the
/// information that will be changed.</param>
/// <param name="tableName">The name of the table that contains the movie.</param>
/// <returns>A Boolean value that indicates the success of the operation.</returns>
public static async Task<bool> UpdateItemAsync(
AmazonDynamoDBClient client,
Movie newMovie,
MovieInfo newInfo,
string tableName)
{
var key = new Dictionary<string, AttributeValue>
{
["title"] = new AttributeValue { S = newMovie.Title },
["year"] = new AttributeValue { N = newMovie.Year.ToString() },
};
var updates = new Dictionary<string, AttributeValueUpdate>
{
["info.plot"] = new AttributeValueUpdate
{
Action = AttributeAction.PUT,
Value = new AttributeValue { S = newInfo.Plot },
},
["info.rating"] = new AttributeValueUpdate
{
Action = AttributeAction.PUT,
Value = new AttributeValue { N = newInfo.Rank.ToString() },
},
};
var request = new UpdateItemRequest
{
AttributeUpdates = updates,
Key = key,
TableName = tableName,
};
var response = await client.UpdateItemAsync(request);
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
LocalStack
- DynamoDB API
- PartiQL for DynamoDB
DynamoDB API
Linux
awslocal dynamodb update-item \
--table-name Music \
--key '{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}' \
--update-expression "SET AlbumTitle = :newval" \
--expression-attribute-values '{":newval":{"S":"Updated Album Title"}}' \
--return-values ALL_NEW{
"Items": [
{
"Artist": {
"S": "Acme Band"
},
"Awards": {
"N": "10"
},
"AlbumTitle": {
"S": "Updated Album Title"
},
"SongTitle": {
"S": "Happy Day"
}
}
]
}
PartiQL for DynamoDB
Linux
awslocal dynamodb execute-statement --statement "UPDATE Music \
SET AlbumTitle='Updated Album Title' \
WHERE Artist='Acme Band' AND SongTitle='Happy Day' \
RETURNING ALL NEW *"{
"Items": [
{
"Artist": {
"S": "Acme Band"
},
"Awards": {
"N": "10"
},
"AlbumTitle": {
"S": "Updated Album Title"
},
"SongTitle": {
"S": "Happy Day"
}
}
]
}
Delete table
- AWS Management Console
- AWS CLI
- AWS SDK
- LocalStack
AWS Management Console
To delete the Music table using the console:
- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- In the left navigation pane, choose Tables.
- Choose the checkbox beside the Music table in the table list.
- Choose Delete.
AWS CLI
The following AWS CLI example deletes the Music table using delete-table.
aws dynamodb delete-table --table-name Music
AWS SDK
Java
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class DeleteTable {
public static void main(String[] args) {
final String usage = """
Usage:
<tableName>
Where:
tableName - The Amazon DynamoDB table to delete (for example, Music3).
**Warning** This program will delete the table that you specify!
""";
if (args.length != 1) {
System.out.println(usage);
System.exit(1);
}
String tableName = args[0];
System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName);
Region region = Region.US_EAST_1;
DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();
deleteDynamoDBTable(ddb, tableName);
ddb.close();
}
public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {
DeleteTableRequest request = DeleteTableRequest.builder()
.tableName(tableName)
.build();
try {
ddb.deleteTable(request);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println(tableName + " was successfully deleted!");
}
}
LocalStack
awslocal dynamodb delete-table --table-name Music
awslocal dynamodb list-tables --region us-east-1
Query data in a table
In this step, you query the data that you wrote to the Music table in Write data to a table by specifying Artist. This will display all songs that are associated with the partition key: Artist.
- AWS Management Console
- AWS CLI
- AWS SDK
- LocalStack
AWS Management Console
Follow these steps to use the DynamoDB console to query data in the Music table.
- Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
- In the left navigation pane, choose Tables.
- Choose the Music table from the table list.
- Choose Explore table items.
- In Scan or query items, make sure that Query is selected.
- For Partition key, enter Acme Band, and then choose Run.
AWS CLI
- DynamoDB API
- PartiQL for DynamoDB
AWS SDK
Java
Queries a table by using DynamoDbClient.
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.HashMap;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*
* To query items from an Amazon DynamoDB table using the AWS SDK for Java V2,
* its better practice to use the
* Enhanced Client. See the EnhancedQueryRecords example.
*/
public class Query {
public static void main(String[] args) {
final String usage = """
Usage:
<tableName> <partitionKeyName> <partitionKeyVal>
Where:
tableName - The Amazon DynamoDB table to put the item in (for example, Music3).
partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist).
partitionKeyVal - The value of the partition key that should match (for example, Famous Band).
""";
if (args.length != 3) {
System.out.println(usage);
System.exit(1);
}
String tableName = args[0];
String partitionKeyName = args[1];
String partitionKeyVal = args[2];
// For more information about an alias, see:
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html
String partitionAlias = "#a";
System.out.format("Querying %s", tableName);
System.out.println("");
Region region = Region.US_EAST_1;
DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();
int count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal, partitionAlias);
System.out.println("There were " + count + " record(s) returned");
ddb.close();
}
public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal,
String partitionAlias) {
// Set up an alias for the partition key name in case it's a reserved word.
HashMap<String, String> attrNameAlias = new HashMap<String, String>();
attrNameAlias.put(partitionAlias, partitionKeyName);
// Set up mapping of the partition name with the value.
HashMap<String, AttributeValue> attrValues = new HashMap<>();
attrValues.put(":" + partitionKeyName, AttributeValue.builder()
.s(partitionKeyVal)
.build());
QueryRequest queryReq = QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression(partitionAlias + " = :" + partitionKeyName)
.expressionAttributeNames(attrNameAlias)
.expressionAttributeValues(attrValues)
.build();
try {
QueryResponse response = ddb.query(queryReq);
return response.count();
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return -1;
}
}
LocalStack
- DynamoDB API
- PartiQL for DynamoDB
📄️ DynamoDB Start
- What is Amazon DynamoDB?
📄️ DynamodDB Streams
- Working with streams
🗃️ Examples
6 items
📄️ References
Amazon DynamoDB Tutorial — A Comprehensive Guide To DynamoDB