### Install DAX Go SDK Sample Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-go-2.md Downloads and installs the sample AWS DAX Go v2 application using the go get command. ```bash go get github.com/aws-samples/sample-aws-dax-go-v2 ``` -------------------------------- ### DynamoDB Getting Started Movies Scenario Bash Script Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_GettingStartedMovies_section.md This Bash script outlines the DynamoDB getting started scenario for creating an Amazon DynamoDB table and performing a series of operations. It is part of a larger example set available on GitHub. ```bash ############################################################################### # function dynamodb_getting_started_movies # # Scenario to create an Amazon DynamoDB table and perform a series of operations on the table. # # Returns: # 0 - If successful. ``` -------------------------------- ### DynamoDB Getting Started Demo in PHP Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_GettingStartedMovies_section.md This script initializes a DynamoDB demo, creating a table, adding, updating, and deleting items. It prompts the user for movie details and ratings, showcasing various DynamoDB operations. ```php namespace DynamoDb\Basics; use Aws\DynamoDb\Marshaler; use DynamoDb; use DynamoDb\DynamoDBAttribute; use DynamoDb\DynamoDBService; use function AwsUtilities\loadMovieData; use function AwsUtilities\testable_readline; class GettingStartedWithDynamoDB { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon DynamoDB getting started demo using PHP!\n"); echo("--------------------------------------\n"); $uuid = uniqid(); $service = new DynamoDBService(); $tableName = "ddb_demo_table_$uuid"; $service->createTable( $tableName, [ new DynamoDBAttribute('year', 'N', 'HASH'), new DynamoDBAttribute('title', 'S', 'RANGE') ] ); echo "Waiting for table..."; $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]); echo "table $tableName found!\n"; echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $service->putItem([ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], 'TableName' => $tableName, ]); echo "How would you rate the movie from 1-10?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } echo "What was the movie about?\n"; while (empty($plot)) { $plot = testable_readline("Plot summary: "); } $key = [ 'Item' => [ 'title' => [ 'S' => $movieName, ], 'year' => [ 'N' => $movieYear, ], ] ]; $attributes = ["rating" => [ 'AttributeName' => 'rating', 'AttributeType' => 'N', 'Value' => $rating, ], 'plot' => [ 'AttributeName' => 'plot', 'AttributeType' => 'S', 'Value' => $plot, ] ]; $service->updateItemAttributesByKey($tableName, $key, $attributes); echo "Movie added and updated."; $batch = json_decode(loadMovieData()); $service->writeBatch($tableName, $batch); $movie = $service->getItemByKey($tableName, $key); echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n"; echo "What rating would you like to give {$movie['Item']['title']['S']}?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating); $movie = $service->getItemByKey($tableName, $key); echo "Ok, you have rated {$movie['Item']['title']['S']} as a {$movie['Item']['rating']['N']}\n"; $service->deleteItemByKey($tableName, $key); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n"; $birthYear = "not a number"; while (!is_numeric($birthYear) || $birthYear >= date("Y")) { $birthYear = testable_readline("Birth year: "); } $birthKey = [ 'Key' => [ 'year' => [ 'N' => "$birthYear", ], ], ]; $result = $service->query($tableName, $birthKey); $marshal = new Marshaler(); echo "Here are the movies in our collection released the year you were born:\n"; $oops = "Oops! There were no movies released in that year (that we know of).\n"; $display = ""; ``` -------------------------------- ### V1 DAX Go SDK GetItem Example Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-go-migrating.md Demonstrates how to create a DAX client and perform a GetItem operation using the V1 SDK. Ensure you have the necessary AWS SDK and DAX Go SDK V1 packages installed. ```go package main import ( "fmt" "os" "github.com/aws/aws-dax-go/dax" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" ) func main() { region := "us-west-2" endpoint := "dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com" // Create session sess, err := session.NewSession(&aws.Config{ Region: aws.String(region), }) if err != nil { fmt.Printf("Failed to create session: %v\n", err) os.Exit(1) } // Configure DAX client cfg := dax.DefaultConfig() cfg.HostPorts = []string{endpoint} cfg.Region = region // Create DAX client daxClient, err := dax.New(cfg) if err != nil { fmt.Printf("Failed to create DAX client: %v\n", err) os.Exit(1) } defer daxClient.Close() // Don't forget to close the client // Create GetItem input input := &dynamodb.GetItemInput{ TableName: aws.String("TryDaxTable"), Key: map[string]*dynamodb.AttributeValue{ "pk": { N: aws.String("1"), }, "sk": { N: aws.String("1"), }, }, } // Make the GetItem call result, err := daxClient.GetItem(input) if err != nil { fmt.Printf("Failed to get item: %v\n", err) os.Exit(1) } // Print the result fmt.Printf("GetItem succeeded: %+v\n", result) } ``` -------------------------------- ### DynamoDB Client Initialization and Table Listing in C++ Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Hello_section.md This snippet shows how to set up the AWS SDK for C++, create a DynamoDB client, and list tables. It's useful for a basic integration test or a starting point for DynamoDB applications. Ensure the AWS SDK for C++ is correctly installed and configured. ```cpp #include #include #include #include /* * A "Hello DynamoDB" starter application which initializes an Amazon DynamoDB (DynamoDB) client and lists the * DynamoDB tables. * * main function * * Usage: 'hello_dynamodb' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::DynamoDB::DynamoDBClient dynamodbClient(clientConfig); Aws::DynamoDB::Model::ListTablesRequest listTablesRequest; listTablesRequest.SetLimit(50); do { const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamodbClient.ListTables( listTablesRequest); if (!outcome.IsSuccess()) { std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl; result = 1; break; } for (const auto &tableName: outcome.GetResult().GetTableNames()) { std::cout << tableName << std::endl; } listTablesRequest.SetExclusiveStartTableName( outcome.GetResult().GetLastEvaluatedTableName()); } while (!listTablesRequest.GetExclusiveStartTableName().empty()); } Aws::ShutdownAPI(options); // Should only be called once. return result; } ``` -------------------------------- ### DynamoDB Getting Started Scenario in C++ Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_GettingStartedMovies_section.md This C++ code orchestrates a DynamoDB scenario, including creating a table, running the main scenario logic, and deleting the table. It requires the AWS SDK for C++. ```cpp { Aws::Client::ClientConfiguration clientConfig; // 1. Create a table with partition: year (N) and sort: title (S). (CreateTable) if (AwsDoc::DynamoDB::createMoviesDynamoDBTable(clientConfig)) { AwsDoc::DynamoDB::dynamodbGettingStartedScenario(clientConfig); // 9. Delete the table. (DeleteTable) AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(clientConfig); } } ``` -------------------------------- ### V2 DAX Go SDK GetItem Example Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-go-migrating.md Illustrates how to initialize a DAX client and execute a GetItem request using the V2 SDK. This version utilizes context, V2 AWS SDK components, and attributevalue marshaling for type safety. Ensure you have the V2 AWS SDK and DAX Go SDK V2 packages installed. ```go package main import ( "context" "fmt" "os" "github.com/aws/aws-dax-go-v2/dax" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" "github.com/aws/aws-sdk-go-v2/aws" ) func main() { ctx := context.Background() region := "us-west-2" endpoint := "dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com" // Create DAX config config := dax.DefaultConfig() // Specify Endpoint and Region config.HostPorts = []string{endpoint} config.Region = region // Enabling logging config.LogLevel = utils.LogDebug // Create DAX client daxClient, err := dax.New(config) if err != nil { fmt.Printf("Failed to create DAX client: %v\n", err) os.Exit(1) } defer daxClient.Close() // Don't forget to close the client // Create key using attributevalue.Marshal for type safety pk, err := attributevalue.Marshal(fmt.Sprintf("%s_%d", keyPrefix, i)) if err != nil { return fmt.Errorf("error marshaling pk: %v", err) } sk, err := attributevalue.Marshal(fmt.Sprintf("%d", j)) if err != nil { return fmt.Errorf("error marshaling sk: %v", err) } // Create GetItem input input := &dynamodb.GetItemInput{ TableName: aws.String("TryDaxTable"), Key: map[string]types.AttributeValue{ "pk": pk, "sk": sk, }, } // Make the GetItem call result, err := daxClient.GetItem(ctx, input) if err != nil { fmt.Printf("Failed to get item: %v\n", err) os.Exit(1) } // Print the result fmt.Printf("GetItem succeeded: %+v\n", result) } ``` -------------------------------- ### Install Go (Golang) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-go-2.md Installs the Go programming language using yum. This is a prerequisite for running Go applications. ```bash sudo yum install -y golang ``` -------------------------------- ### Verify Go Installation Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-go-2.md Checks if the Go programming language is installed and running correctly by displaying its version. ```bash go version ``` -------------------------------- ### Verify .NET SDK Installation Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-dotnet.md Aliases the dotnet command and verifies the installed .NET SDK version. If an error occurs, install the libunwind package. ```bash alias dotnet=$HOME/dotnet/dotnet dotnet --version ``` ```bash sudo yum install -y libunwind ``` -------------------------------- ### Install PIP Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TicTacToe.Phase1.md Installs the Python Package Installer (PIP) using the get-pip.py script. Ensure you run this command in a command terminal as an administrator. ```bash python.exe get-pip.py ``` -------------------------------- ### Test Node.js Installation Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-nodejs.md Verifies that Node.js is installed and running by checking its version. ```javascript node -e "console.log('Running Node.js ' + process.version)" ``` -------------------------------- ### Install DAX Node.js Client Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-nodejs.md Installs the Amazon DynamoDB Accelerator (DAX) Node.js client using npm. ```bash npm install amazon-dax-client ``` -------------------------------- ### Install Node.js using nvm Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-nodejs.md Installs a specific version of Node.js (12.16.3) using nvm. ```bash nvm install 12.16.3 ``` -------------------------------- ### AssumeRoleWithWebIdentity GET Request Example Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WIF.RunningYourApp.md This is a sample GET request to AWS STS for the AssumeRoleWithWebIdentity action. It includes parameters like ProviderId, DurationSeconds, RoleArn, and WebIdentityToken. ```http GET / HTTP/1.1 Host: sts.amazonaws.com Content-Type: application/json; charset=utf-8 URL: https://sts.amazonaws.com/?ProviderId=www.amazon.com &DurationSeconds=900&Action=AssumeRoleWithWebIdentity &Version=2011-06-15&RoleSessionName=web-identity-federation &RoleArn=arn:aws:iam::123456789012:role/GameRole &WebIdentityToken=Atza|IQEBLjAsAhQluyKqyBiYZ8-kclvGTYM81e...(remaining characters omitted) ``` -------------------------------- ### Example Usage of Conditional Operations Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_ConditionalOperations_section.md Demonstrates the practical application of conditional operations in DynamoDB, including setting up example keys and initiating conditional updates. This serves as a starting point for testing conditional logic. ```java public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) { // Example key Map key = new HashMap<>(); key.put("ProductId", AttributeValue.builder().s("P12345").build()); System.out.println("Demonstrating conditional operations in DynamoDB"); try { // Example 1: Conditional update System.out.println("\nExample 1: Conditional update"); Map updateResult = conditionalUpdate( ``` -------------------------------- ### Download Sample Program Source Code Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-nodejs.md Downloads the sample application source code ZIP file. ```bash wget http://docs.aws.amazon.com/amazondb/latest/developerguide/samples/TryDax.zip ``` -------------------------------- ### Start DynamoDB Local Server Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.md Command to start the DynamoDB local server. Ensure you have Java Runtime Environment (JRE) version 17.x or newer installed. The `-sharedDb` flag allows DynamoDB to persist data across restarts. ```bash java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb ``` -------------------------------- ### Update Nested Attribute with Dots using Boto3 Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_ExpressionAttributeNames_section.md Update a nested DynamoDB attribute using dot notation for the path. This example requires Boto3 to be installed and configured. ```python import boto3 from botocore.exceptions import ClientError from typing import Any, Dict, List def update_nested_attribute_with_dots( table_name: str, key: Dict[str, Any], path_with_dots: str, value: Any ) -> Dict[str, Any]: """ Update a nested attribute using a path with dot notation. This function demonstrates how to use expression attribute names to work with nested attributes specified using dot notation. Args: table_name (str): The name of the DynamoDB table. key (Dict[str, Any]): The primary key of the item to update. path_with_dots (str): The path to the nested attribute using dot notation (e.g., "a.b.c"). value (Any): The value to set for the nested attribute. Returns: Dict[str, Any]: The response from DynamoDB containing the updated attribute values. """ # Initialize the DynamoDB resource dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(table_name) ``` -------------------------------- ### Create and Load Sample Data with AWS SDK for .NET Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/AppendixSampleDataCodeDotNET.md This is the main entry point for the sample application. It orchestrates the deletion of existing tables, creation of new tables, and loading of sample data. It includes basic error handling for AWS service exceptions. ```C# using System; using System.Collections.Generic; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.SecurityToken; namespace com.amazonaws.codesamples { class CreateTablesLoadData { private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); static void Main(string[] args) { try { //DeleteAllTables(client); DeleteTable("ProductCatalog"); DeleteTable("Forum"); DeleteTable("Thread"); DeleteTable("Reply"); // Create tables (using the AWS SDK for .NET low-level API). CreateTableProductCatalog(); CreateTableForum(); CreateTableThread(); // ForumTitle, Subject */ CreateTableReply(); // Load data (using the .NET SDK document API) LoadSampleProducts(); LoadSampleForums(); LoadSampleThreads(); LoadSampleReplies(); Console.WriteLine("Sample complete!"); Console.WriteLine("Press ENTER to continue"); Console.ReadLine(); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } private static void DeleteTable(string tableName) { try { var deleteTableResponse = client.DeleteTable(new DeleteTableRequest() { TableName = tableName }); WaitTillTableDeleted(client, tableName, deleteTableResponse); } catch (ResourceNotFoundException) { // There is no such table. } } private static void CreateTableProductCatalog() { string tableName = "ProductCatalog"; var response = client.CreateTable(new CreateTableRequest { TableName = tableName, AttributeDefinitions = new List() { new AttributeDefinition { AttributeName = "Id", AttributeType = "N" } }, KeySchema = new List() { new KeySchemaElement { AttributeName = "Id", KeyType = "HASH" } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 10, WriteCapacityUnits = 5 } }); WaitTillTableCreated(client, tableName, response); } private static void CreateTableForum() { string tableName = "Forum"; var response = client.CreateTable(new CreateTableRequest { TableName = tableName, AttributeDefinitions = new List() { new AttributeDefinition { AttributeName = "Name", AttributeType = "S" } }, KeySchema = new List() { new KeySchemaElement { AttributeName = "Name", // forum Title KeyType = "HASH" } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 10, WriteCapacityUnits = 5 } }); WaitTillTableCreated(client, tableName, response); } private static void CreateTableThread() { string tableName = "Thread"; var response = client.CreateTable(new CreateTableRequest { TableName = tableName, ``` -------------------------------- ### Run DAX Sample Programs (Create Table and Write Data) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-dotnet.md Copies and runs .NET sample programs to create a DynamoDB table and write data to it. This process is repeated for each sample program. ```bash cp TryDax/dotNet/01-CreateTable.cs myApp/Program.cs dotnet run --project myApp cp TryDax/dotNet/02-Write-Data.cs myApp/Program.cs dotnet run --project myApp ``` -------------------------------- ### DynamoDBMapper Query Secondary Index Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.Methods.md Queries a global secondary index for items. This example shows how to retrieve messages posted by a specific user, starting with a certain string. ```APIDOC ## POST /query (Index) ### Description Queries a global secondary index for items matching the provided key conditions. This method does not support strongly consistent reads. ### Method POST ### Endpoint (Implicitly through DynamoDBMapper.query method with index specified) ### Parameters #### Request Body - **queryExpression** (DynamoDBQueryExpression) - Required - An expression defining the query criteria for the index. - **indexName** (String) - Required - The name of the global secondary index to query. - **consistentRead** (Boolean) - Required - Must be set to `false` for global secondary indexes. ### Request Example ```java HashMap eav = new HashMap(); eav.put(":v1", new AttributeValue().withS("User A")); eav.put(":v2", new AttributeValue().withS("DynamoDB")); DynamoDBQueryExpression queryExpression = new DynamoDBQueryExpression() .withIndexName("PostedBy-Message-Index") .withConsistentRead(false) .withKeyConditionExpression("PostedBy = :v1 and begins_with(Message, :v2)") .withExpressionAttributeValues(eav); List iList = mapper.query(PostedByMessage.class, queryExpression); ``` ### Response #### Success Response (200) - **List** - A collection of PostedByMessage objects matching the index query criteria. #### Response Example (Collection of PostedByMessage objects) ``` -------------------------------- ### Get Single Movie with ExecuteStatement (.NET) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_ExecuteStatement_section.md Retrieve a single movie from a DynamoDB table using a PartiQL SELECT statement. This example shows how to filter results by title and retrieve all attributes. ```.cs /// /// Uses a PartiQL SELECT statement to retrieve a single movie from the /// movie database. /// /// The name of the movie table. /// The title of the movie to retrieve. /// A list of movie data. If no movie matches the supplied /// title, the list is empty. public static async Task>> GetSingleMovie(string tableName, string movieTitle) { string selectSingle = $"SELECT * FROM {tableName} WHERE title = ?"; var parameters = new List { new AttributeValue { S = movieTitle }, }; var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest { Statement = selectSingle, Parameters = parameters, }); return response.Items; } ``` -------------------------------- ### Get Item using DynamoDB Client (Kotlin) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_GetItem_section.md Retrieve a specific item from a DynamoDB table using the AWS SDK for Kotlin. This example uses a suspend function and requires the region to be set. ```kotlin suspend fun getSpecificItem( tableNameVal: String, keyName: String, keyVal: String, ) { val keyToGet = mutableMapOf() keyToGet[keyName] = AttributeValue.S(keyVal) val request = GetItemRequest { key = keyToGet tableName = tableNameVal } DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb -> val returnedItem = ddb.getItem(request) val numbersMap = returnedItem.item numbersMap?.forEach { key1 -> println(key1.key) println(key1.value) } } } ``` -------------------------------- ### Get Item using DynamoDB Document Client (JavaScript v3) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_GetItem_section.md Use the DynamoDB Document Client for simplified item operations in JavaScript v3. Ensure the AWS SDK is installed and configured. ```javascript import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new GetCommand({ TableName: "AngryAnimals", Key: { CommonName: "Shoebill", }, }); const response = await docClient.send(command); console.log(response); return response; }; ``` -------------------------------- ### Download Sample Data Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/EMRforDynamoDB.Tutorial.LoadDataIntoHDFS.md Use wget to download the sample data archive. ```bash wget https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/samples/features.zip ``` -------------------------------- ### Example Usage of query_with_datetime Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_DateTimeQueries_section.md This Python function demonstrates how to query a DynamoDB table for items within a specific date and time range. Ensure you have the necessary AWS SDK for Python (Boto3) installed and configured. ```python from datetime import datetime, timedelta def example_usage(): """Example of how to use the query_with_datetime function.""" # Example parameters table_name = "Events" partition_key_name = "EventType" partition_key_value = "UserLogin" sort_key_name = "Timestamp" # Create date/time variables for the query end_date = datetime.now() start_date = end_date - timedelta(days=7) # Query events from the last 7 days print(f"Querying events from {start_date.isoformat()} to {end_date.isoformat()}") # Execute the query response = query_with_datetime( table_name, partition_key_name, partition_key_value, sort_key_name, start_date, end_date ) # Process the results items = response.get("Items", []) print(f"Found {len(items)} items") for item in items: print(f"Event: {item}") ``` -------------------------------- ### Get DynamoDB Local Help Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.UsageNotes.md Prints a usage summary and available command-line options for DynamoDB Local. ```bash java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help ``` -------------------------------- ### Install DAX Python Client Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-python.md Install the necessary DAX Python client library using pip. This is a prerequisite for running the sample application. ```bash pip install amazon-dax-client ``` -------------------------------- ### Activate Virtual Environment and Install Dependencies Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.Tutorial2.md Activates the project's virtual environment and installs required Python packages. ```bash source .venv/bin/activate python -m pip install -r requirements.txt ``` -------------------------------- ### Get Multiple Items with BatchExecuteStatement (.NET) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_BatchExecuteStatement_section.md Use BatchExecuteStatement to retrieve multiple items from a DynamoDB table using PartiQL SELECT statements. This example demonstrates fetching two specific movies by title and year. ```.cs new BatchStatementRequest { Statement = getBatch, Parameters = new List { new AttributeValue { S = title1 }, new AttributeValue { N = year1.ToString() }, }, }, new BatchStatementRequest { Statement = getBatch, Parameters = new List { new AttributeValue { S = title2 }, new AttributeValue { N = year2.ToString() }, }, } }; var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest { Statements = statements, }); if (response.Responses.Count > 0) { response.Responses.ForEach(r => { if (r.Item.Any()) { Console.WriteLine($"{r.Item["title"]}\t{r.Item["year"]}"); } }); return true; } else { Console.WriteLine($"Couldn't find either {title1} or {title2}."); return false; } ``` -------------------------------- ### Run DAX Sample Programs (GetItem, Query, Scan) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-dotnet.md Copies and runs .NET sample programs for GetItem, Query, and Scan operations on the DAX cluster. Requires specifying the DAX cluster endpoint as a command-line parameter. ```bash cp TryDax/dotNet/03-GetItem-Test.cs myApp/Program.cs dotnet run --project myApp {{dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com}} cp TryDax/dotNet/04-Query-Test.cs myApp/Program.cs dotnet run --project myApp {{dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com}} cp TryDax/dotNet/05-Scan-Test.cs myApp/Program.cs ``` -------------------------------- ### Describe DynamoDB Table TTL using Boto3 Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_DescribeTimeToLive_section.md This snippet shows how to call the DescribeTimeToLive API to get the TTL configuration for a specific DynamoDB table. Ensure you have the AWS SDK for Python (Boto3) installed and configured. ```python describe_ttl("your-table-name", "us-east-1") ``` -------------------------------- ### Get Movie Item with Python (Boto3) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_GetItem_section.md Retrieves a movie item from a DynamoDB table using its 'year' and 'title' as the composite key. This example is part of a larger class for interacting with a movie table and requires the Boto3 SDK. ```python class Movies: """Encapsulates an Amazon DynamoDB table of movie data. Example data structure for a movie record in this table: { "year": 1999, "title": "For Love of the Game", "info": { "directors": ["Sam Raimi"], "release_date": "1999-09-15T00:00:00Z", "rating": 6.3, "plot": "A washed up pitcher flashes through his career.", "rank": 4987, "running_time_secs": 8220, "actors": [ "Kevin Costner", "Kelly Preston", "John C. Reilly" ] } } """ def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource # The table variable is set during the scenario in the call to # 'exists' if the table exists. Otherwise, it is set by 'create_table'. self.table = None def get_movie(self, title, year): """ Gets movie data from the table for a specific movie. :param title: The title of the movie. :param year: The release year of the movie. :return: The data about the requested movie. """ try: response = self.table.get_item(Key={"year": year, "title": title}) except ClientError as err: logger.error( "Couldn't get movie %s from table %s. Here's why: %s: %s", title, self.table.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["Item"] ``` -------------------------------- ### Run DynamoDB PartiQL Scenario Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_PartiQLBatch_section.md Initializes DynamoDB resources and runs a scenario demonstrating PartiQL batch operations. Includes error handling for the entire process. ```python if __name__ == "__main__": try: dyn_res = boto3.resource("dynamodb") scaffold = Scaffold(dyn_res) movies = PartiQLBatchWrapper(dyn_res) run_scenario(scaffold, movies, "doc-example-table-partiql-movies") except Exception as e: print(f"Something went wrong with the demo! Here's what: {e}") ``` -------------------------------- ### View Sample Data Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/EMRforDynamoDB.Tutorial.LoadDataIntoHDFS.md Use the head command to view the first few lines of the features.txt file to verify extraction. ```bash head features.txt ``` -------------------------------- ### DynamoDB PartiQL Batch Operations with Java Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_Scenario_PartiQLBatch_section.md This example demonstrates creating a DynamoDB table, performing batch put, get, update, and delete operations using PartiQL, and finally deleting the table. It requires the AWS SDK for Java 2.x. ```Java public class ScenarioPartiQLBatch { public static void main(String[] args) throws IOException { String tableName = "MoviesPartiQBatch"; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); System.out.println("Creating an Amazon DynamoDB table named " + tableName + " with a key named year and a sort key named title."); createTable(ddb, tableName); System.out.println("Adding multiple records into the " + tableName + " table using a batch command."); putRecordBatch(ddb); // Update multiple movies by using the BatchExecute statement. String title1 = "Star Wars"; int year1 = 1977; String title2 = "Wizard of Oz"; int year2 = 1939; System.out.println("Query two movies."); getBatch(ddb, tableName, title1, title2, year1, year2); System.out.println("Updating multiple records using a batch command."); updateTableItemBatch(ddb); System.out.println("Deleting multiple records using a batch command."); deleteItemBatch(ddb); System.out.println("Deleting the Amazon DynamoDB table."); deleteDynamoDBTable(ddb, tableName); ddb.close(); } public static boolean getBatch(DynamoDbClient ddb, String tableName, String title1, String title2, int year1, int year2) { String getBatch = "SELECT * FROM " + tableName + " WHERE title = ? AND year = ?"; List statements = new ArrayList<>(); statements.add(BatchStatementRequest.builder() .statement(getBatch) .parameters(AttributeValue.builder().s(title1).build(), AttributeValue.builder().n(String.valueOf(year1)).build()) .build()); statements.add(BatchStatementRequest.builder() .statement(getBatch) .parameters(AttributeValue.builder().s(title2).build(), AttributeValue.builder().n(String.valueOf(year2)).build()) .build()); BatchExecuteStatementRequest batchExecuteStatementRequest = BatchExecuteStatementRequest.builder() .statements(statements) .build(); try { BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchExecuteStatementRequest); if (!response.responses().isEmpty()) { response.responses().forEach(r -> { System.out.println(r.item().get("title") + "\t" + r.item().get("year")); }); return true; } else { System.out.println("Couldn't find either " + title1 + " or " + title2 + "."); return false; } } catch (DynamoDbException e) { System.err.println(e.getMessage()); return false; } } public static void createTable(DynamoDbClient ddb, String tableName) { DynamoDbWaiter dbWaiter = ddb.waiter(); ArrayList attributeDefinitions = new ArrayList<>(); // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() .attributeName("year") .attributeType("N") .build()); attributeDefinitions.add(AttributeDefinition.builder() .attributeName("title") .attributeType("S") .build()); ArrayList tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() .attributeName("year") .keyType(KeyType.HASH) .build(); KeySchemaElement key2 = KeySchemaElement.builder() .attributeName("title") .keyType(KeyType.RANGE) // Sort .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() .keySchema(tableKey) .billingMode(BillingMode.PAY_PER_REQUEST) // DynamoDB automatically scales based on traffic. .attributeDefinitions(attributeDefinitions) .tableName(tableName) .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() .tableName(tableName) .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse waiterResponse = dbWaiter .waitUntilTableExists(tableRequest); ``` -------------------------------- ### Run .NET Project Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-dotnet.md Executes the .NET project located in the 'myApp' directory. ```bash dotnet run --project myApp ``` -------------------------------- ### Get Batch Items with Paginator using DynamoDB Service Client (Java) Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_BatchGetItem_section.md Retrieves batch items from a DynamoDB table using a paginator for handling potentially large result sets. Requires AWS SDK for Java 2.x setup. ```java 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.BatchGetItemRequest; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class BatchGetItemsPaginator { public static void main(String[] args){ final String usage = """ Usage: Where: tableName - The Amazon DynamoDB table (for example, Music).\s """; String tableName = "Music"; Region region = Region.US_EAST_1; DynamoDbClient dynamoDbClient = DynamoDbClient.builder() .region(region) .build(); getBatchItemsPaginator(dynamoDbClient, tableName) ; } public static void getBatchItemsPaginator(DynamoDbClient dynamoDbClient, String tableName) { // Define the primary key values for the items you want to retrieve. Map key1 = new HashMap<>(); key1.put("Artist", AttributeValue.builder().s("Artist1").build()); Map key2 = new HashMap<>(); key2.put("Artist", AttributeValue.builder().s("Artist2").build()); // Construct the batchGetItem request. Map requestItems = new HashMap<>(); requestItems.put(tableName, KeysAndAttributes.builder() .keys(List.of(key1, key2)) ``` -------------------------------- ### Create DynamoDB Table with Go SDK Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.run-application-go-2.md Runs the sample Go application to create a DynamoDB table named TryDaxGoTable. ```bash go run ~/go/pkg/mod/github.com/aws-samples/sample-aws-dax-go-v2@v1.0.0/try_dax.go -service dynamodb -command create-table ``` -------------------------------- ### Get Item from DynamoDB Table Source: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_GetItem_section.md Retrieves a single item from a specified DynamoDB table using its primary key. Ensure your AWS credentials and SDK are configured. This example uses the low-level DynamoDbClient; for enhanced features, consider the Enhanced Client. ```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: 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 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 returnedItem = ddb.getItem(request).item(); if (returnedItem.isEmpty()) System.out.format("No item found with the key %s!\n", key); else { Set 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); } } } ```