버전 4(V4) AWS SDK for .NET 가 릴리스되었습니다.
변경 사항 해제 및 애플리케이션 마이그레이션에 대한 자세한 내용은 마이그레이션 주제를 참조하세요.
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
SDK for .NET (v4)를 사용한 DynamoDB 예제
다음 코드 예제에서는 DynamoDB에서 AWS SDK for .NET (v4)를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.
기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.
작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 관련 시나리오의 컨텍스트에 따라 표시되며, 개별 서비스 함수를 직접적으로 호출하는 방법을 보여줍니다.
각 예시에는 전체 소스 코드에 대한 링크가 포함되어 있으며, 여기에서 컨텍스트에 맞춰 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있습니다.
시작
다음 코드 예제에서는 DynamoDB를 사용하여 시작하는 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리
에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요. using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Microsoft.Extensions.DependencyInjection; namespace DynamoDBActions; /// <summary> /// A simple example that demonstrates basic DynamoDB operations. /// </summary> public class HelloDynamoDB { /// <summary> /// HelloDynamoDB lists the existing DynamoDB tables for the default user. /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Async task.</returns> static async Task Main(string[] args) { // Set up dependency injection for Amazon DynamoDB. using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonDynamoDB>() ) .Build(); // Now the client is available for injection. var dynamoDbClient = host.Services.GetRequiredService<IAmazonDynamoDB>(); try { var request = new ListTablesRequest(); var tableNames = new List<string>(); var paginatorForTables = dynamoDbClient.Paginators.ListTables(request); await foreach (var tableName in paginatorForTables.TableNames) { tableNames.Add(tableName); } Console.WriteLine("Welcome to the DynamoDB Hello Service example. " + "\nLet's list your DynamoDB tables:"); tableNames.ForEach(table => { Console.WriteLine($"Table: {table}"); }); } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB service error occurred while listing tables. {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"An error occurred while listing tables. {ex.Message}"); } } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 ListTables를 참조하세요.
-
기본 사항
다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.
영화 데이터를 저장할 수 있는 테이블을 생성합니다.
테이블에 하나의 영화를 추가하고 가져오고 업데이트합니다.
샘플 JSON 파일에서 테이블에 영화 데이터를 씁니다.
특정 연도에 개봉된 영화를 쿼리합니다.
특정 연도 범위 동안 개봉된 영화를 스캔합니다.
테이블에서 영화를 삭제한 다음, 테이블을 삭제합니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리
에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// This example application performs the following basic Amazon DynamoDB /// functions: /// CreateTableAsync /// PutItemAsync /// UpdateItemAsync /// BatchWriteItemAsync /// GetItemAsync /// DeleteItemAsync /// Query /// Scan /// DeleteItemAsync. /// </summary> public class DynamoDbBasics { public static bool IsInteractive = true; // Separator for the console display. private static readonly string SepBar = new string('-', 80); /// <summary> /// The main entry point for the DynamoDB Basics example application. /// </summary> /// <param name="args">Command line arguments.</param> /// <returns>A task representing the asynchronous operation.</returns> public static async Task Main(string[] args) { // Set up dependency injection for Amazon DynamoDB. using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonDynamoDB>() .AddTransient<DynamoDbWrapper>()) .Build(); // Now the wrapper is available for injection. var dynamoDbWrapper = host.Services.GetRequiredService<DynamoDbWrapper>(); var tableName = "movie_table"; var movieFileName = @"movies.json"; DisplayInstructions(); // Create a new table and wait for it to be active. Console.WriteLine($"Creating the new table: {tableName}"); var success = await dynamoDbWrapper.CreateMovieTableAsync(tableName); Console.WriteLine(success ? $"\nTable: {tableName} successfully created." : $"\nCould not create {tableName}."); WaitForEnter(); // Add a single new movie to the table. var newMovie = new Movie { Year = 2021, Title = "Spider-Man: No Way Home", }; success = await dynamoDbWrapper.PutItemAsync(newMovie, tableName); if (success) { Console.WriteLine($"Added {newMovie.Title} to the table."); } else { Console.WriteLine("Could not add movie to table."); } WaitForEnter(); // Update the new movie by adding a plot and rank. var newInfo = new MovieInfo { Plot = "With Spider-Man's identity now revealed, Peter asks" + "Doctor Strange for help. When a spell goes wrong, dangerous" + "foes from other worlds start to appear, forcing Peter to" + "discover what it truly means to be Spider-Man.", Rank = 9, }; success = await dynamoDbWrapper.UpdateItemAsync(newMovie, newInfo, tableName); if (success) { Console.WriteLine($"Successfully updated the movie: {newMovie.Title}"); } else { Console.WriteLine("Could not update the movie."); } WaitForEnter(); // Add a batch of movies to the DynamoDB table from a list of // movies in a JSON file. var itemCount = await dynamoDbWrapper.BatchWriteItemsAsync(movieFileName, tableName); Console.WriteLine($"Added {itemCount} movies to the table."); WaitForEnter(); // Get a movie by key. (partition + sort) var lookupMovie = new Movie { Title = "Jurassic Park", Year = 1993, }; Console.WriteLine("Looking for the movie \"Jurassic Park\"."); var item = await dynamoDbWrapper.GetItemAsync(lookupMovie, tableName); if (item?.Count > 0) { dynamoDbWrapper.DisplayItem(item); } else { Console.WriteLine($"Couldn't find {lookupMovie.Title}"); } WaitForEnter(); // Delete a movie. var movieToDelete = new Movie { Title = "The Town", Year = 2010, }; success = await dynamoDbWrapper.DeleteItemAsync(tableName, movieToDelete); if (success) { Console.WriteLine($"Successfully deleted {movieToDelete.Title}."); } else { Console.WriteLine($"Could not delete {movieToDelete.Title}."); } WaitForEnter(); // Use Query to find all the movies released in 2010. int findYear = 2010; Console.WriteLine($"Movies released in {findYear}"); var queryCount = await dynamoDbWrapper.QueryMoviesAsync(tableName, findYear); Console.WriteLine($"Found {queryCount} movies released in {findYear}"); WaitForEnter(); // Use Scan to get a list of movies from 2001 to 2011. int startYear = 2001; int endYear = 2011; var scanCount = await dynamoDbWrapper.ScanTableAsync(tableName, startYear, endYear); Console.WriteLine($"Found {scanCount} movies released between {startYear} and {endYear}"); WaitForEnter(); // Delete the table. success = await dynamoDbWrapper.DeleteTableAsync(tableName); if (success) { Console.WriteLine($"Successfully deleted {tableName}"); } else { Console.WriteLine($"Could not delete {tableName}"); } Console.WriteLine("The DynamoDB Basics example application is complete."); WaitForEnter(); } /// <summary> /// Displays the description of the application on the console. /// </summary> private static void DisplayInstructions() { if (!IsInteractive) { return; } Console.Clear(); Console.WriteLine(); Console.Write(new string(' ', 28)); Console.WriteLine("DynamoDB Basics Example"); Console.WriteLine(SepBar); Console.WriteLine("This demo application shows the basics of using DynamoDB with the AWS SDK."); Console.WriteLine(SepBar); Console.WriteLine("The application does the following:"); Console.WriteLine("\t1. Creates a table with partition: year and sort:title."); Console.WriteLine("\t2. Adds a single movie to the table."); Console.WriteLine("\t3. Adds movies to the table from moviedata.json."); Console.WriteLine("\t4. Updates the rating and plot of the movie that was just added."); Console.WriteLine("\t5. Gets a movie using its key (partition + sort)."); Console.WriteLine("\t6. Deletes a movie."); Console.WriteLine("\t7. Uses QueryAsync to return all movies released in a given year."); Console.WriteLine("\t8. Uses ScanAsync to return all movies released within a range of years."); Console.WriteLine("\t9. Finally, it deletes the table that was just created."); WaitForEnter(); } /// <summary> /// Simple method to wait for the Enter key to be pressed. /// </summary> private static void WaitForEnter() { if (IsInteractive) { Console.WriteLine("\nPress <Enter> to continue."); Console.WriteLine(SepBar); _ = Console.ReadLine(); } } }
영화 데이터를 포함할 테이블을 생성합니다.
/// <summary> /// Creates a new Amazon DynamoDB table and then waits for the new /// table to become active. /// </summary> /// <param name="tableName">The name of the table to create.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> CreateMovieTableAsync(string tableName) { try { var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest { TableName = tableName, AttributeDefinitions = new List<AttributeDefinition>() { new AttributeDefinition { AttributeName = "title", AttributeType = ScalarAttributeType.S, }, new AttributeDefinition { AttributeName = "year", AttributeType = ScalarAttributeType.N, }, }, KeySchema = new List<KeySchemaElement>() { new KeySchemaElement { AttributeName = "year", KeyType = KeyType.HASH, }, new KeySchemaElement { AttributeName = "title", KeyType = KeyType.RANGE, }, }, BillingMode = BillingMode.PAY_PER_REQUEST, }); // Wait until the table is ACTIVE and then report success. Console.Write("Waiting for table to become active..."); var request = new DescribeTableRequest { TableName = response.TableDescription.TableName, }; TableStatus status; int sleepDuration = 2000; do { Thread.Sleep(sleepDuration); var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request); status = describeTableResponse.Table.TableStatus; Console.Write("."); } while (status != "ACTIVE"); return status == TableStatus.ACTIVE; } catch (ResourceInUseException ex) { Console.WriteLine($"Table {tableName} already exists. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}"); throw; } }
테이블에 하나의 영화를 추가합니다.
/// <summary> /// Adds a new item to the table. /// </summary> /// <param name="newMovie">A Movie object containing informtation for /// the movie to add to the table.</param> /// <param name="tableName">The name of the table where the item will be added.</param> /// <returns>A Boolean value that indicates the results of adding the item.</returns> public async Task<bool> PutItemAsync(Movie newMovie, string tableName) { try { var item = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new PutItemRequest { TableName = tableName, Item = item, }; await _amazonDynamoDB.PutItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while putting item. {ex.Message}"); throw; } }
테이블에서 하나의 항목을 업데이트합니다.
/// <summary> /// Updates an existing item in the movies table. /// </summary> /// <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 async Task<bool> UpdateItemAsync( Movie newMovie, MovieInfo newInfo, string tableName) { try { 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, }; await _amazonDynamoDB.UpdateItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while updating item. {ex.Message}"); throw; } }
영화 테이블에서 하나의 항목을 가져옵니다.
/// <summary> /// Gets information about an existing movie from the table. /// </summary> /// <param name="newMovie">A Movie object containing information about /// the movie to retrieve.</param> /// <param name="tableName">The name of the table containing the movie.</param> /// <returns>A Dictionary object containing information about the item /// retrieved.</returns> public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new GetItemRequest { Key = key, TableName = tableName, }; var response = await _amazonDynamoDB.GetItemAsync(request); return response.Item; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return new Dictionary<string, AttributeValue>(); } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while getting item. {ex.Message}"); throw; } }
영화 테이블에 항목 배치를 씁니다.
/// <summary> /// Loads the contents of a JSON file into a list of movies to be /// added to the DynamoDB table. /// </summary> /// <param name="movieFileName">The name of the JSON file.</param> /// <returns>A generic list of movie objects.</returns> public List<Movie> ImportMovies(string movieFileName) { var moviesList = new List<Movie>(); if (!File.Exists(movieFileName)) { return moviesList; } using var sr = new StreamReader(movieFileName); string json = sr.ReadToEnd(); var allMovies = JsonSerializer.Deserialize<List<Movie>>( json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); // Now return the first 250 entries. if (allMovies != null && allMovies.Any()) { moviesList = allMovies.GetRange(0, 250); } return moviesList; } /// <summary> /// Writes 250 items to the movie table. /// </summary> /// <param name="movieFileName">A string containing the full path to /// the JSON file containing movie data.</param> /// <param name="tableName">The name of the table to write items to.</param> /// <returns>A long integer value representing the number of movies /// imported from the JSON file.</returns> public async Task<long> BatchWriteItemsAsync( string movieFileName, string tableName) { try { var movies = ImportMovies(movieFileName); if (!movies.Any()) { Console.WriteLine("Couldn't find the JSON file with movie data."); return 0; } var context = new DynamoDBContextBuilder() // Optional call to provide a specific instance of IAmazonDynamoDB .WithDynamoDBClient(() => _amazonDynamoDB) .Build(); var movieBatch = context.CreateBatchWrite<Movie>( new BatchWriteConfig() { OverrideTableName = tableName }); movieBatch.AddPutItems(movies); Console.WriteLine("Adding imported movies to the table."); await movieBatch.ExecuteAsync(); return movies.Count; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table was not found during batch write operation. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred during batch write operation. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred during batch write operation. {ex.Message}"); throw; } }
테이블에서 하나의 항목을 삭제합니다.
/// <summary> /// Deletes a single item from a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table from which the item /// will be deleted.</param> /// <param name="movieToDelete">A movie object containing the title and /// year of the movie to delete.</param> /// <returns>A Boolean value indicating the success or failure of the /// delete operation.</returns> public async Task<bool> DeleteItemAsync( string tableName, Movie movieToDelete) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = movieToDelete.Title }, ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() }, }; var request = new DeleteItemRequest { TableName = tableName, Key = key, }; await _amazonDynamoDB.DeleteItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting item. {ex.Message}"); throw; } }
테이블에서 특정 연도에 릴리스된 영화를 쿼리합니다.
/// <summary> /// Queries the table for movies released in a particular year and /// then displays the information for the movies returned. /// </summary> /// <param name="tableName">The name of the table to query.</param> /// <param name="year">The release year for which we want to /// view movies.</param> /// <returns>The number of movies that match the query.</returns> public async Task<int> QueryMoviesAsync(string tableName, int year) { try { var movieTable = new TableBuilder(_amazonDynamoDB, tableName) .AddHashKey("year", DynamoDBEntryType.Numeric) .AddRangeKey("title", DynamoDBEntryType.String) .Build(); var filter = new QueryFilter("year", QueryOperator.Equal, year); Console.WriteLine("\nFind movies released in: {year}:"); var config = new QueryOperationConfig() { Limit = 10, // 10 items per page. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "title", "year", }, ConsistentRead = true, Filter = filter, }; // Value used to track how many movies match the // supplied criteria. var moviesFound = 0; var search = movieTable.Query(config); do { var movieList = await search.GetNextSetAsync(); moviesFound += movieList.Count; foreach (var movie in movieList) { DisplayDocument(movie); } } while (!search.IsDone); return moviesFound; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while querying movies. {ex.Message}"); throw; } }
테이블에서 특정 연도 범위 동안 릴리스된 영화를 스캔합니다.
/// <summary> /// Scans the table for movies released between the specified years. /// </summary> /// <param name="tableName">The name of the table to scan.</param> /// <param name="startYear">The starting year for the range.</param> /// <param name="endYear">The ending year for the range.</param> /// <returns>The number of movies found in the specified year range.</returns> public async Task<int> ScanTableAsync( string tableName, int startYear, int endYear) { try { var request = new ScanRequest { TableName = tableName, ExpressionAttributeNames = new Dictionary<string, string> { { "#yr", "year" }, }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":y_a", new AttributeValue { N = startYear.ToString() } }, { ":y_z", new AttributeValue { N = endYear.ToString() } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs", Limit = 10 // Set a limit to demonstrate using the LastEvaluatedKey. }; // Keep track of how many movies were found. int foundCount = 0; var response = new ScanResponse(); do { response = await _amazonDynamoDB.ScanAsync(request); foundCount += response.Items.Count; response.Items.ForEach(i => DisplayItem(i)); request.ExclusiveStartKey = response.LastEvaluatedKey; } while (response?.LastEvaluatedKey?.Count > 0); return foundCount; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while scanning table. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while scanning table. {ex.Message}"); throw; } }
영화 테이블을 삭제합니다.
/// <summary> /// Deletes a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteTableAsync(string tableName) { try { var request = new DeleteTableRequest { TableName = tableName, }; var response = await _amazonDynamoDB.DeleteTableAsync(request); Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted."); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}"); return false; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 다음 주제를 참조하세요.
-
작업
다음 코드 예시는 BatchWriteItem
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리
에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요. 영화 테이블에 항목 배치를 씁니다.
/// <summary> /// Loads the contents of a JSON file into a list of movies to be /// added to the DynamoDB table. /// </summary> /// <param name="movieFileName">The name of the JSON file.</param> /// <returns>A generic list of movie objects.</returns> public List<Movie> ImportMovies(string movieFileName) { var moviesList = new List<Movie>(); if (!File.Exists(movieFileName)) { return moviesList; } using var sr = new StreamReader(movieFileName); string json = sr.ReadToEnd(); var allMovies = JsonSerializer.Deserialize<List<Movie>>( json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); // Now return the first 250 entries. if (allMovies != null && allMovies.Any()) { moviesList = allMovies.GetRange(0, 250); } return moviesList; } /// <summary> /// Writes 250 items to the movie table. /// </summary> /// <param name="movieFileName">A string containing the full path to /// the JSON file containing movie data.</param> /// <param name="tableName">The name of the table to write items to.</param> /// <returns>A long integer value representing the number of movies /// imported from the JSON file.</returns> public async Task<long> BatchWriteItemsAsync( string movieFileName, string tableName) { try { var movies = ImportMovies(movieFileName); if (!movies.Any()) { Console.WriteLine("Couldn't find the JSON file with movie data."); return 0; } var context = new DynamoDBContextBuilder() // Optional call to provide a specific instance of IAmazonDynamoDB .WithDynamoDBClient(() => _amazonDynamoDB) .Build(); var movieBatch = context.CreateBatchWrite<Movie>( new BatchWriteConfig() { OverrideTableName = tableName }); movieBatch.AddPutItems(movies); Console.WriteLine("Adding imported movies to the table."); await movieBatch.ExecuteAsync(); return movies.Count; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table was not found during batch write operation. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred during batch write operation. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred during batch write operation. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 BatchWriteItem을 참조하세요.
-
다음 코드 예시는 CreateTable
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Creates a new Amazon DynamoDB table and then waits for the new /// table to become active. /// </summary> /// <param name="tableName">The name of the table to create.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> CreateMovieTableAsync(string tableName) { try { var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest { TableName = tableName, AttributeDefinitions = new List<AttributeDefinition>() { new AttributeDefinition { AttributeName = "title", AttributeType = ScalarAttributeType.S, }, new AttributeDefinition { AttributeName = "year", AttributeType = ScalarAttributeType.N, }, }, KeySchema = new List<KeySchemaElement>() { new KeySchemaElement { AttributeName = "year", KeyType = KeyType.HASH, }, new KeySchemaElement { AttributeName = "title", KeyType = KeyType.RANGE, }, }, BillingMode = BillingMode.PAY_PER_REQUEST, }); // Wait until the table is ACTIVE and then report success. Console.Write("Waiting for table to become active..."); var request = new DescribeTableRequest { TableName = response.TableDescription.TableName, }; TableStatus status; int sleepDuration = 2000; do { Thread.Sleep(sleepDuration); var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request); status = describeTableResponse.Table.TableStatus; Console.Write("."); } while (status != "ACTIVE"); return status == TableStatus.ACTIVE; } catch (ResourceInUseException ex) { Console.WriteLine($"Table {tableName} already exists. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 CreateTable을 참조하세요.
-
다음 코드 예시는 DeleteItem
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Deletes a single item from a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table from which the item /// will be deleted.</param> /// <param name="movieToDelete">A movie object containing the title and /// year of the movie to delete.</param> /// <returns>A Boolean value indicating the success or failure of the /// delete operation.</returns> public async Task<bool> DeleteItemAsync( string tableName, Movie movieToDelete) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = movieToDelete.Title }, ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() }, }; var request = new DeleteItemRequest { TableName = tableName, Key = key, }; await _amazonDynamoDB.DeleteItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting item. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 DeleteItem을 참조하세요.
-
다음 코드 예시는 DeleteTable
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Deletes a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteTableAsync(string tableName) { try { var request = new DeleteTableRequest { TableName = tableName, }; var response = await _amazonDynamoDB.DeleteTableAsync(request); Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted."); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}"); return false; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 DeleteTable을 참조하세요.
-
다음 코드 예시는 GetItem
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Gets information about an existing movie from the table. /// </summary> /// <param name="newMovie">A Movie object containing information about /// the movie to retrieve.</param> /// <param name="tableName">The name of the table containing the movie.</param> /// <returns>A Dictionary object containing information about the item /// retrieved.</returns> public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new GetItemRequest { Key = key, TableName = tableName, }; var response = await _amazonDynamoDB.GetItemAsync(request); return response.Item; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return new Dictionary<string, AttributeValue>(); } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while getting item. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 GetItem을 참조하세요.
-
다음 코드 예시는 PutItem
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Adds a new item to the table. /// </summary> /// <param name="newMovie">A Movie object containing informtation for /// the movie to add to the table.</param> /// <param name="tableName">The name of the table where the item will be added.</param> /// <returns>A Boolean value that indicates the results of adding the item.</returns> public async Task<bool> PutItemAsync(Movie newMovie, string tableName) { try { var item = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new PutItemRequest { TableName = tableName, Item = item, }; await _amazonDynamoDB.PutItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while putting item. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 PutItem을 참조하세요.
-
다음 코드 예시는 Query
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Queries the table for movies released in a particular year and /// then displays the information for the movies returned. /// </summary> /// <param name="tableName">The name of the table to query.</param> /// <param name="year">The release year for which we want to /// view movies.</param> /// <returns>The number of movies that match the query.</returns> public async Task<int> QueryMoviesAsync(string tableName, int year) { try { var movieTable = new TableBuilder(_amazonDynamoDB, tableName) .AddHashKey("year", DynamoDBEntryType.Numeric) .AddRangeKey("title", DynamoDBEntryType.String) .Build(); var filter = new QueryFilter("year", QueryOperator.Equal, year); Console.WriteLine("\nFind movies released in: {year}:"); var config = new QueryOperationConfig() { Limit = 10, // 10 items per page. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "title", "year", }, ConsistentRead = true, Filter = filter, }; // Value used to track how many movies match the // supplied criteria. var moviesFound = 0; var search = movieTable.Query(config); do { var movieList = await search.GetNextSetAsync(); moviesFound += movieList.Count; foreach (var movie in movieList) { DisplayDocument(movie); } } while (!search.IsDone); return moviesFound; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while querying movies. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 Query를 참조하세요.
-
다음 코드 예시는 Scan
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Scans the table for movies released between the specified years. /// </summary> /// <param name="tableName">The name of the table to scan.</param> /// <param name="startYear">The starting year for the range.</param> /// <param name="endYear">The ending year for the range.</param> /// <returns>The number of movies found in the specified year range.</returns> public async Task<int> ScanTableAsync( string tableName, int startYear, int endYear) { try { var request = new ScanRequest { TableName = tableName, ExpressionAttributeNames = new Dictionary<string, string> { { "#yr", "year" }, }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":y_a", new AttributeValue { N = startYear.ToString() } }, { ":y_z", new AttributeValue { N = endYear.ToString() } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs", Limit = 10 // Set a limit to demonstrate using the LastEvaluatedKey. }; // Keep track of how many movies were found. int foundCount = 0; var response = new ScanResponse(); do { response = await _amazonDynamoDB.ScanAsync(request); foundCount += response.Items.Count; response.Items.ForEach(i => DisplayItem(i)); request.ExclusiveStartKey = response.LastEvaluatedKey; } while (response?.LastEvaluatedKey?.Count > 0); return foundCount; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while scanning table. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while scanning table. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 Scan을 참조하세요.
-
다음 코드 예시는 UpdateItem
의 사용 방법을 보여 줍니다.
- SDK for .NET (v4)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Updates an existing item in the movies table. /// </summary> /// <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 async Task<bool> UpdateItemAsync( Movie newMovie, MovieInfo newInfo, string tableName) { try { 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, }; await _amazonDynamoDB.UpdateItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while updating item. {ex.Message}"); throw; } }
-
API 세부 정보는 AWS SDK for .NET API 참조의 UpdateItem을 참조하세요.
-