次のコード例は、以下を実行する方法を示しています。
複数の SELECT ステートメントを実行して、項目のバッチを取得する。
複数の INSERT ステートメントを実行して、項目のバッチを追加する。
複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
複数の DELETE ステートメントを実行して、項目のバッチを削除する。
- AWS SDK for .NET
-
注記
GitHub には、その他のリソースもあります。AWS コード例リポジトリ
で全く同じ例を見つけて、設定と実行の方法を確認してください。 // Before you run this example, download 'movies.json' from // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html, // and put it in the same folder as the example. // Separator for the console display. var SepBar = new string('-', 80); const string tableName = "movie_table"; const string movieFileName = "moviedata.json"; DisplayInstructions(); // Create the table and wait for it to be active. Console.WriteLine($"Creating the movie table: {tableName}"); var success = await DynamoDBMethods.CreateMovieTableAsync(tableName); if (success) { Console.WriteLine($"Successfully created table: {tableName}."); } WaitForEnter(); // Add movie information to the table from moviedata.json. See the // instructions at the top of this file to download the JSON file. Console.WriteLine($"Inserting movies into the new table. Please wait..."); success = await PartiQLBatchMethods.InsertMovies(tableName, movieFileName); if (success) { Console.WriteLine("Movies successfully added to the table."); } else { Console.WriteLine("Movies could not be added to the table."); } WaitForEnter(); // Update multiple movies by using the BatchExecute statement. var title1 = "Star Wars"; var year1 = 1977; var title2 = "Wizard of Oz"; var year2 = 1939; Console.WriteLine($"Updating two movies with producer information: {title1} and {title2}."); success = await PartiQLBatchMethods.GetBatch(tableName, title1, title2, year1, year2); if (success) { Console.WriteLine($"Successfully retrieved {title1} and {title2}."); } else { Console.WriteLine("Select statement failed."); } WaitForEnter(); // Update multiple movies by using the BatchExecute statement. var producer1 = "LucasFilm"; var producer2 = "MGM"; Console.WriteLine($"Updating two movies with producer information: {title1} and {title2}."); success = await PartiQLBatchMethods.UpdateBatch(tableName, producer1, title1, year1, producer2, title2, year2); if (success) { Console.WriteLine($"Successfully updated {title1} and {title2}."); } else { Console.WriteLine("Update failed."); } WaitForEnter(); // Delete multiple movies by using the BatchExecute statement. Console.WriteLine($"Now we will delete {title1} and {title2} from the table."); success = await PartiQLBatchMethods.DeleteBatch(tableName, title1, year1, title2, year2); if (success) { Console.WriteLine($"Deleted {title1} and {title2}"); } else { Console.WriteLine($"could not delete {title1} or {title2}"); } WaitForEnter(); // DNow that the PartiQL Batch scenario is complete, delete the movie table. success = await DynamoDBMethods.DeleteTableAsync(tableName); if (success) { Console.WriteLine($"Successfully deleted {tableName}"); } else { Console.WriteLine($"Could not delete {tableName}"); } /// <summary> /// Displays the description of the application on the console. /// </summary> void DisplayInstructions() { Console.Clear(); Console.WriteLine(); Console.Write(new string(' ', 24)); Console.WriteLine("DynamoDB PartiQL Basics Example"); Console.WriteLine(SepBar); Console.WriteLine("This demo application shows the basics of using Amazon DynamoDB with the AWS SDK for"); Console.WriteLine(".NET version 3.7 and .NET 6."); Console.WriteLine(SepBar); Console.WriteLine("Creates a table by using the CreateTable method."); Console.WriteLine("Gets multiple movies by using a PartiQL SELECT statement."); Console.WriteLine("Updates multiple movies by using the ExecuteBatch method."); Console.WriteLine("Deletes multiple movies by using a PartiQL DELETE statement."); Console.WriteLine("Cleans up the resources created for the demo by deleting the table."); Console.WriteLine(SepBar); WaitForEnter(); } /// <summary> /// Simple method to wait for the <Enter> key to be pressed. /// </summary> void WaitForEnter() { Console.WriteLine("\nPress <Enter> to continue."); Console.Write(SepBar); _ = Console.ReadLine(); } /// <summary> /// Gets movies from the movie table by /// using an Amazon DynamoDB PartiQL SELECT statement. /// </summary> /// <param name="tableName">The name of the table.</param> /// <param name="title1">The title of the first movie.</param> /// <param name="title2">The title of the second movie.</param> /// <param name="year1">The year of the first movie.</param> /// <param name="year2">The year of the second movie.</param> /// <returns>True if successful.</returns> public static async Task<bool> GetBatch( string tableName, string title1, string title2, int year1, int year2) { var getBatch = $"SELECT FROM {tableName} WHERE title = ? AND year = ?"; var statements = new List<BatchStatementRequest> { new BatchStatementRequest { Statement = getBatch, Parameters = new List<AttributeValue> { new AttributeValue { S = title1 }, new AttributeValue { N = year1.ToString() }, }, }, new BatchStatementRequest { Statement = getBatch, Parameters = new List<AttributeValue> { 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 => { Console.WriteLine($"{r.Item["title"]}\t{r.Item["year"]}"); }); return true; } else { Console.WriteLine($"Couldn't find either {title1} or {title2}."); return false; } } /// <summary> /// Inserts movies imported from a JSON file into the movie table by /// using an Amazon DynamoDB PartiQL INSERT statement. /// </summary> /// <param name="tableName">The name of the table into which the movie /// information will be inserted.</param> /// <param name="movieFileName">The name of the JSON file that contains /// movie information.</param> /// <returns>A Boolean value that indicates the success or failure of /// the insert operation.</returns> public static async Task<bool> InsertMovies(string tableName, string movieFileName) { // Get the list of movies from the JSON file. var movies = ImportMovies(movieFileName); var success = false; if (movies is not null) { // Insert the movies in a batch using PartiQL. Because the // batch can contain a maximum of 25 items, insert 25 movies // at a time. string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}"; var statements = new List<BatchStatementRequest>(); try { for (var indexOffset = 0; indexOffset < 250; indexOffset += 25) { for (var i = indexOffset; i < indexOffset + 25; i++) { statements.Add(new BatchStatementRequest { Statement = insertBatch, Parameters = new List<AttributeValue> { new AttributeValue { S = movies[i].Title }, new AttributeValue { N = movies[i].Year.ToString() }, }, }); } var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest { Statements = statements, }); // Wait between batches for movies to be successfully added. System.Threading.Thread.Sleep(3000); success = response.HttpStatusCode == System.Net.HttpStatusCode.OK; // Clear the list of statements for the next batch. statements.Clear(); } } catch (AmazonDynamoDBException ex) { Console.WriteLine(ex.Message); } } return success; } /// <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 full path to the JSON file.</param> /// <returns>A generic list of movie objects.</returns> public static List<Movie> ImportMovies(string movieFileName) { if (!File.Exists(movieFileName)) { return null!; } using var sr = new StreamReader(movieFileName); string json = sr.ReadToEnd(); var allMovies = JsonConvert.DeserializeObject<List<Movie>>(json); if (allMovies is not null) { // Return the first 250 entries. return allMovies.GetRange(0, 250); } else { return null!; } } /// <summary> /// Updates information for multiple movies. /// </summary> /// <param name="tableName">The name of the table containing the /// movies to be updated.</param> /// <param name="producer1">The producer name for the first movie /// to update.</param> /// <param name="title1">The title of the first movie.</param> /// <param name="year1">The year that the first movie was released.</param> /// <param name="producer2">The producer name for the second /// movie to update.</param> /// <param name="title2">The title of the second movie.</param> /// <param name="year2">The year that the second movie was released.</param> /// <returns>A Boolean value that indicates the success of the update.</returns> public static async Task<bool> UpdateBatch( string tableName, string producer1, string title1, int year1, string producer2, string title2, int year2) { string updateBatch = $"UPDATE {tableName} SET Producer=? WHERE title = ? AND year = ?"; var statements = new List<BatchStatementRequest> { new BatchStatementRequest { Statement = updateBatch, Parameters = new List<AttributeValue> { new AttributeValue { S = producer1 }, new AttributeValue { S = title1 }, new AttributeValue { N = year1.ToString() }, }, }, new BatchStatementRequest { Statement = updateBatch, Parameters = new List<AttributeValue> { new AttributeValue { S = producer2 }, new AttributeValue { S = title2 }, new AttributeValue { N = year2.ToString() }, }, } }; var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest { Statements = statements, }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Deletes multiple movies using a PartiQL BatchExecuteAsync /// statement. /// </summary> /// <param name="tableName">The name of the table containing the /// moves that will be deleted.</param> /// <param name="title1">The title of the first movie.</param> /// <param name="year1">The year the first movie was released.</param> /// <param name="title2">The title of the second movie.</param> /// <param name="year2">The year the second movie was released.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public static async Task<bool> DeleteBatch( string tableName, string title1, int year1, string title2, int year2) { string updateBatch = $"DELETE FROM {tableName} WHERE title = ? AND year = ?"; var statements = new List<BatchStatementRequest> { new BatchStatementRequest { Statement = updateBatch, Parameters = new List<AttributeValue> { new AttributeValue { S = title1 }, new AttributeValue { N = year1.ToString() }, }, }, new BatchStatementRequest { Statement = updateBatch, Parameters = new List<AttributeValue> { new AttributeValue { S = title2 }, new AttributeValue { N = year2.ToString() }, }, } }; var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest { Statements = statements, }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
-
API の詳細については、「AWS SDK for .NET API リファレンス」の「BatchExecuteStatement」を参照してください。
-
AWS SDK デベロッパーガイドとコード例の詳細なリストについては、「AWS SDK で DynamoDB を使用する」を参照してください。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。