Contoh DynamoDB menggunakan untuk Kotlin SDK - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Contoh DynamoDB menggunakan untuk Kotlin SDK

Contoh kode berikut menunjukkan cara melakukan tindakan dan mengimplementasikan skenario umum dengan menggunakan AWS SDK for Kotlin dengan DynamoDB.

Dasar-dasar adalah contoh kode yang menunjukkan kepada Anda bagaimana melakukan operasi penting dalam suatu layanan.

Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.

Skenario adalah contoh kode yang menunjukkan kepada Anda bagaimana menyelesaikan tugas tertentu dengan memanggil beberapa fungsi dalam layanan atau dikombinasikan dengan yang lain Layanan AWS.

Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.

Hal-hal mendasar

Contoh kode berikut ini menunjukkan cara:

  • Buat tabel yang dapat menyimpan data film.

  • Masukkan, dapatkan, dan perbarui satu film dalam tabel tersebut.

  • Tulis data film ke tabel dari JSON file sampel.

  • Kueri untuk film yang dirilis pada tahun tertentu.

  • Pindai film yang dirilis dalam suatu rentang tahun.

  • Hapus film dari tabel, lalu hapus tabel tersebut.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat tabel DynamoDB.

suspend fun createScenarioTable( tableNameVal: String, key: String, ) { val attDef = AttributeDefinition { attributeName = key attributeType = ScalarAttributeType.N } val attDef1 = AttributeDefinition { attributeName = "title" attributeType = ScalarAttributeType.S } val keySchemaVal = KeySchemaElement { attributeName = key keyType = KeyType.Hash } val keySchemaVal1 = KeySchemaElement { attributeName = "title" keyType = KeyType.Range } val provisionedVal = ProvisionedThroughput { readCapacityUnits = 10 writeCapacityUnits = 10 } val request = CreateTableRequest { attributeDefinitions = listOf(attDef, attDef1) keySchema = listOf(keySchemaVal, keySchemaVal1) provisionedThroughput = provisionedVal tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.createTable(request) ddb.waitUntilTableExists { // suspend call tableName = tableNameVal } println("The table was successfully created ${response.tableDescription?.tableArn}") } }

Buat fungsi pembantu untuk mengunduh dan mengekstrak JSON file sampel.

// Load data into the table. suspend fun loadData( tableName: String, fileName: String, ) { val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val iter: Iterator<JsonNode> = rootNode.iterator() var currentNode: ObjectNode var t = 0 while (iter.hasNext()) { if (t == 50) { break } currentNode = iter.next() as ObjectNode val year = currentNode.path("year").asInt() val title = currentNode.path("title").asText() val info = currentNode.path("info").toString() putMovie(tableName, year, title, info) t++ } } suspend fun putMovie( tableNameVal: String, year: Int, title: String, info: String, ) { val itemValues = mutableMapOf<String, AttributeValue>() val strVal = year.toString() // Add all content to the table. itemValues["year"] = AttributeValue.N(strVal) itemValues["title"] = AttributeValue.S(title) itemValues["info"] = AttributeValue.S(info) val request = PutItemRequest { tableName = tableNameVal item = itemValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.putItem(request) println("Added $title to the Movie table.") } }

Dapatkan item dari tabel.

suspend fun getMovie( tableNameVal: String, keyName: String, keyVal: String, ) { val keyToGet = mutableMapOf<String, AttributeValue>() keyToGet[keyName] = AttributeValue.N(keyVal) keyToGet["title"] = AttributeValue.S("King Kong") val request = GetItemRequest { key = keyToGet tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val returnedItem = ddb.getItem(request) val numbersMap = returnedItem.item numbersMap?.forEach { key1 -> println(key1.key) println(key1.value) } } }

Contoh lengkap.

suspend fun main(args: Array<String>) { val usage = """ Usage: <fileName> Where: fileName - The path to the moviedata.json you can download from the Amazon DynamoDB Developer Guide. """ if (args.size != 1) { println(usage) exitProcess(1) } // Get the moviedata.json from the Amazon DynamoDB Developer Guide. val tableName = "Movies" val fileName = args[0] val partitionAlias = "#a" println("Creating an Amazon DynamoDB table named Movies with a key named id and a sort key named title.") createScenarioTable(tableName, "year") loadData(tableName, fileName) getMovie(tableName, "year", "1933") scanMovies(tableName) val count = queryMovieTable(tableName, "year", partitionAlias) println("There are $count Movies released in 2013.") deletIssuesTable(tableName) } suspend fun createScenarioTable( tableNameVal: String, key: String, ) { val attDef = AttributeDefinition { attributeName = key attributeType = ScalarAttributeType.N } val attDef1 = AttributeDefinition { attributeName = "title" attributeType = ScalarAttributeType.S } val keySchemaVal = KeySchemaElement { attributeName = key keyType = KeyType.Hash } val keySchemaVal1 = KeySchemaElement { attributeName = "title" keyType = KeyType.Range } val provisionedVal = ProvisionedThroughput { readCapacityUnits = 10 writeCapacityUnits = 10 } val request = CreateTableRequest { attributeDefinitions = listOf(attDef, attDef1) keySchema = listOf(keySchemaVal, keySchemaVal1) provisionedThroughput = provisionedVal tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.createTable(request) ddb.waitUntilTableExists { // suspend call tableName = tableNameVal } println("The table was successfully created ${response.tableDescription?.tableArn}") } } // Load data into the table. suspend fun loadData( tableName: String, fileName: String, ) { val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val iter: Iterator<JsonNode> = rootNode.iterator() var currentNode: ObjectNode var t = 0 while (iter.hasNext()) { if (t == 50) { break } currentNode = iter.next() as ObjectNode val year = currentNode.path("year").asInt() val title = currentNode.path("title").asText() val info = currentNode.path("info").toString() putMovie(tableName, year, title, info) t++ } } suspend fun putMovie( tableNameVal: String, year: Int, title: String, info: String, ) { val itemValues = mutableMapOf<String, AttributeValue>() val strVal = year.toString() // Add all content to the table. itemValues["year"] = AttributeValue.N(strVal) itemValues["title"] = AttributeValue.S(title) itemValues["info"] = AttributeValue.S(info) val request = PutItemRequest { tableName = tableNameVal item = itemValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.putItem(request) println("Added $title to the Movie table.") } } suspend fun getMovie( tableNameVal: String, keyName: String, keyVal: String, ) { val keyToGet = mutableMapOf<String, AttributeValue>() keyToGet[keyName] = AttributeValue.N(keyVal) keyToGet["title"] = AttributeValue.S("King Kong") val request = GetItemRequest { key = keyToGet tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val returnedItem = ddb.getItem(request) val numbersMap = returnedItem.item numbersMap?.forEach { key1 -> println(key1.key) println(key1.value) } } } suspend fun deletIssuesTable(tableNameVal: String) { val request = DeleteTableRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.deleteTable(request) println("$tableNameVal was deleted") } } suspend fun queryMovieTable( tableNameVal: String, partitionKeyName: String, partitionAlias: String, ): Int { val attrNameAlias = mutableMapOf<String, String>() attrNameAlias[partitionAlias] = "year" // Set up mapping of the partition name with the value. val attrValues = mutableMapOf<String, AttributeValue>() attrValues[":$partitionKeyName"] = AttributeValue.N("2013") val request = QueryRequest { tableName = tableNameVal keyConditionExpression = "$partitionAlias = :$partitionKeyName" expressionAttributeNames = attrNameAlias this.expressionAttributeValues = attrValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.query(request) return response.count } } suspend fun scanMovies(tableNameVal: String) { val request = ScanRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.scan(request) response.items?.forEach { item -> item.keys.forEach { key -> println("The key name is $key\n") println("The value is ${item[key]}") } } } }

Tindakan

Contoh kode berikut menunjukkan cara menggunakanCreateTable.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun createNewTable( tableNameVal: String, key: String, ): String? { val attDef = AttributeDefinition { attributeName = key attributeType = ScalarAttributeType.S } val keySchemaVal = KeySchemaElement { attributeName = key keyType = KeyType.Hash } val provisionedVal = ProvisionedThroughput { readCapacityUnits = 10 writeCapacityUnits = 10 } val request = CreateTableRequest { attributeDefinitions = listOf(attDef) keySchema = listOf(keySchemaVal) provisionedThroughput = provisionedVal tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> var tableArn: String val response = ddb.createTable(request) ddb.waitUntilTableExists { // suspend call tableName = tableNameVal } tableArn = response.tableDescription!!.tableArn.toString() println("Table $tableArn is ready") return tableArn } }

Contoh kode berikut menunjukkan cara menggunakanDeleteItem.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun deleteDynamoDBItem( tableNameVal: String, keyName: String, keyVal: String, ) { val keyToGet = mutableMapOf<String, AttributeValue>() keyToGet[keyName] = AttributeValue.S(keyVal) val request = DeleteItemRequest { tableName = tableNameVal key = keyToGet } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.deleteItem(request) println("Item with key matching $keyVal was deleted") } }

Contoh kode berikut menunjukkan cara menggunakanDeleteTable.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun deleteDynamoDBTable(tableNameVal: String) { val request = DeleteTableRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.deleteTable(request) println("$tableNameVal was deleted") } }

Contoh kode berikut menunjukkan cara menggunakanGetItem.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun getSpecificItem( tableNameVal: String, keyName: String, keyVal: String, ) { val keyToGet = mutableMapOf<String, AttributeValue>() keyToGet[keyName] = AttributeValue.S(keyVal) val request = GetItemRequest { key = keyToGet tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val returnedItem = ddb.getItem(request) val numbersMap = returnedItem.item numbersMap?.forEach { key1 -> println(key1.key) println(key1.value) } } }
  • Untuk API detailnya, lihat GetItem AWSSDKAPIreferensi Kotlin.

Contoh kode berikut menunjukkan cara menggunakanListTables.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun listAllTables() { DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.listTables(ListTablesRequest {}) response.tableNames?.forEach { tableName -> println("Table name is $tableName") } } }

Contoh kode berikut menunjukkan cara menggunakanPutItem.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun putItemInTable( tableNameVal: String, key: String, keyVal: String, albumTitle: String, albumTitleValue: String, awards: String, awardVal: String, songTitle: String, songTitleVal: String, ) { val itemValues = mutableMapOf<String, AttributeValue>() // Add all content to the table. itemValues[key] = AttributeValue.S(keyVal) itemValues[songTitle] = AttributeValue.S(songTitleVal) itemValues[albumTitle] = AttributeValue.S(albumTitleValue) itemValues[awards] = AttributeValue.S(awardVal) val request = PutItemRequest { tableName = tableNameVal item = itemValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.putItem(request) println(" A new item was placed into $tableNameVal.") } }
  • Untuk API detailnya, lihat PutItem AWSSDKAPIreferensi Kotlin.

Contoh kode berikut menunjukkan cara menggunakanQuery.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun queryDynTable( tableNameVal: String, partitionKeyName: String, partitionKeyVal: String, partitionAlias: String, ): Int { val attrNameAlias = mutableMapOf<String, String>() attrNameAlias[partitionAlias] = partitionKeyName // Set up mapping of the partition name with the value. val attrValues = mutableMapOf<String, AttributeValue>() attrValues[":$partitionKeyName"] = AttributeValue.S(partitionKeyVal) val request = QueryRequest { tableName = tableNameVal keyConditionExpression = "$partitionAlias = :$partitionKeyName" expressionAttributeNames = attrNameAlias this.expressionAttributeValues = attrValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.query(request) return response.count } }
  • Untuk API detailnya, lihat Kueri AWS SDKuntuk API referensi Kotlin.

Contoh kode berikut menunjukkan cara menggunakanScan.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun scanItems(tableNameVal: String) { val request = ScanRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.scan(request) response.items?.forEach { item -> item.keys.forEach { key -> println("The key name is $key\n") println("The value is ${item[key]}") } } } }
  • Untuk API detailnya, lihat Memindai AWS SDKAPIreferensi Kotlin.

Contoh kode berikut menunjukkan cara menggunakanUpdateItem.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun updateTableItem( tableNameVal: String, keyName: String, keyVal: String, name: String, updateVal: String, ) { val itemKey = mutableMapOf<String, AttributeValue>() itemKey[keyName] = AttributeValue.S(keyVal) val updatedValues = mutableMapOf<String, AttributeValueUpdate>() updatedValues[name] = AttributeValueUpdate { value = AttributeValue.S(updateVal) action = AttributeAction.Put } val request = UpdateItemRequest { tableName = tableNameVal key = itemKey attributeUpdates = updatedValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.updateItem(request) println("Item in $tableNameVal was updated") } }

Skenario

Contoh kode berikut menunjukkan cara membuat aplikasi yang mengirimkan data ke tabel Amazon DynamoDB dan memberi tahu Anda saat pengguna memperbarui tabel.

SDKuntuk Kotlin

Menunjukkan cara membuat aplikasi Android asli yang mengirimkan data menggunakan Amazon API DynamoDB Kotlin dan mengirim pesan teks menggunakan Amazon Kotlin. SNS API

Untuk kode sumber lengkap dan instruksi tentang cara mengatur dan menjalankan, lihat contoh lengkapnya di GitHub.

Layanan yang digunakan dalam contoh ini
  • DynamoDB

  • Amazon SNS

Contoh kode berikut menunjukkan cara membuat aplikasi tanpa server yang memungkinkan pengguna mengelola foto menggunakan label.

SDKuntuk Kotlin

Menunjukkan cara mengembangkan aplikasi manajemen aset foto yang mendeteksi label dalam gambar menggunakan Amazon Rekognition dan menyimpannya untuk pengambilan nanti.

Untuk kode sumber lengkap dan instruksi tentang cara mengatur dan menjalankan, lihat contoh lengkapnya di GitHub.

Untuk mendalami tentang asal usul contoh ini, lihat postingan di Komunitas AWS.

Layanan yang digunakan dalam contoh ini
  • APIGerbang

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

Contoh kode berikut menunjukkan cara membuat aplikasi web yang melacak item kerja dalam tabel Amazon DynamoDB dan menggunakan Amazon Simple Email Service (SESAmazon) untuk mengirim laporan.

SDKuntuk Kotlin

Menunjukkan cara menggunakan Amazon API DynamoDB untuk membuat aplikasi web dinamis yang melacak data kerja DynamoDB.

Untuk kode sumber lengkap dan instruksi tentang cara mengatur dan menjalankan, lihat contoh lengkapnya di GitHub.

Layanan yang digunakan dalam contoh ini
  • DynamoDB

  • Amazon SES

Contoh kode berikut ini menunjukkan cara:

  • Dapatkan sekumpulan item dengan menjalankan beberapa SELECT pernyataan.

  • Tambahkan sekumpulan item dengan menjalankan beberapa INSERT pernyataan.

  • Perbarui sekumpulan item dengan menjalankan beberapa UPDATE pernyataan.

  • Hapus sekumpulan item dengan menjalankan beberapa DELETE pernyataan.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun main() { val ddb = DynamoDbClient { region = "us-east-1" } val tableName = "MoviesPartiQBatch" println("Creating an Amazon DynamoDB table named $tableName with a key named id and a sort key named title.") createTablePartiQLBatch(ddb, tableName, "year") putRecordBatch(ddb) updateTableItemBatchBatch(ddb) deleteItemsBatch(ddb) deleteTablePartiQLBatch(tableName) } suspend fun createTablePartiQLBatch( ddb: DynamoDbClient, tableNameVal: String, key: String, ) { val attDef = AttributeDefinition { attributeName = key attributeType = ScalarAttributeType.N } val attDef1 = AttributeDefinition { attributeName = "title" attributeType = ScalarAttributeType.S } val keySchemaVal = KeySchemaElement { attributeName = key keyType = KeyType.Hash } val keySchemaVal1 = KeySchemaElement { attributeName = "title" keyType = KeyType.Range } val provisionedVal = ProvisionedThroughput { readCapacityUnits = 10 writeCapacityUnits = 10 } val request = CreateTableRequest { attributeDefinitions = listOf(attDef, attDef1) keySchema = listOf(keySchemaVal, keySchemaVal1) provisionedThroughput = provisionedVal tableName = tableNameVal } val response = ddb.createTable(request) ddb.waitUntilTableExists { // suspend call tableName = tableNameVal } println("The table was successfully created ${response.tableDescription?.tableArn}") } suspend fun putRecordBatch(ddb: DynamoDbClient) { val sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}" // Create three movies to add to the Amazon DynamoDB table. val parametersMovie1 = mutableListOf<AttributeValue>() parametersMovie1.add(AttributeValue.N("2022")) parametersMovie1.add(AttributeValue.S("My Movie 1")) parametersMovie1.add(AttributeValue.S("No Information")) val statementRequestMovie1 = BatchStatementRequest { statement = sqlStatement parameters = parametersMovie1 } // Set data for Movie 2. val parametersMovie2 = mutableListOf<AttributeValue>() parametersMovie2.add(AttributeValue.N("2022")) parametersMovie2.add(AttributeValue.S("My Movie 2")) parametersMovie2.add(AttributeValue.S("No Information")) val statementRequestMovie2 = BatchStatementRequest { statement = sqlStatement parameters = parametersMovie2 } // Set data for Movie 3. val parametersMovie3 = mutableListOf<AttributeValue>() parametersMovie3.add(AttributeValue.N("2022")) parametersMovie3.add(AttributeValue.S("My Movie 3")) parametersMovie3.add(AttributeValue.S("No Information")) val statementRequestMovie3 = BatchStatementRequest { statement = sqlStatement parameters = parametersMovie3 } // Add all three movies to the list. val myBatchStatementList = mutableListOf<BatchStatementRequest>() myBatchStatementList.add(statementRequestMovie1) myBatchStatementList.add(statementRequestMovie2) myBatchStatementList.add(statementRequestMovie3) val batchRequest = BatchExecuteStatementRequest { statements = myBatchStatementList } val response = ddb.batchExecuteStatement(batchRequest) println("ExecuteStatement successful: " + response.toString()) println("Added new movies using a batch command.") } suspend fun updateTableItemBatchBatch(ddb: DynamoDbClient) { val sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?" val parametersRec1 = mutableListOf<AttributeValue>() parametersRec1.add(AttributeValue.N("2022")) parametersRec1.add(AttributeValue.S("My Movie 1")) val statementRequestRec1 = BatchStatementRequest { statement = sqlStatement parameters = parametersRec1 } // Update record 2. val parametersRec2 = mutableListOf<AttributeValue>() parametersRec2.add(AttributeValue.N("2022")) parametersRec2.add(AttributeValue.S("My Movie 2")) val statementRequestRec2 = BatchStatementRequest { statement = sqlStatement parameters = parametersRec2 } // Update record 3. val parametersRec3 = mutableListOf<AttributeValue>() parametersRec3.add(AttributeValue.N("2022")) parametersRec3.add(AttributeValue.S("My Movie 3")) val statementRequestRec3 = BatchStatementRequest { statement = sqlStatement parameters = parametersRec3 } // Add all three movies to the list. val myBatchStatementList = mutableListOf<BatchStatementRequest>() myBatchStatementList.add(statementRequestRec1) myBatchStatementList.add(statementRequestRec2) myBatchStatementList.add(statementRequestRec3) val batchRequest = BatchExecuteStatementRequest { statements = myBatchStatementList } val response = ddb.batchExecuteStatement(batchRequest) println("ExecuteStatement successful: $response") println("Updated three movies using a batch command.") println("Items were updated!") } suspend fun deleteItemsBatch(ddb: DynamoDbClient) { // Specify three records to delete. val sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?" val parametersRec1 = mutableListOf<AttributeValue>() parametersRec1.add(AttributeValue.N("2022")) parametersRec1.add(AttributeValue.S("My Movie 1")) val statementRequestRec1 = BatchStatementRequest { statement = sqlStatement parameters = parametersRec1 } // Specify record 2. val parametersRec2 = mutableListOf<AttributeValue>() parametersRec2.add(AttributeValue.N("2022")) parametersRec2.add(AttributeValue.S("My Movie 2")) val statementRequestRec2 = BatchStatementRequest { statement = sqlStatement parameters = parametersRec2 } // Specify record 3. val parametersRec3 = mutableListOf<AttributeValue>() parametersRec3.add(AttributeValue.N("2022")) parametersRec3.add(AttributeValue.S("My Movie 3")) val statementRequestRec3 = BatchStatementRequest { statement = sqlStatement parameters = parametersRec3 } // Add all three movies to the list. val myBatchStatementList = mutableListOf<BatchStatementRequest>() myBatchStatementList.add(statementRequestRec1) myBatchStatementList.add(statementRequestRec2) myBatchStatementList.add(statementRequestRec3) val batchRequest = BatchExecuteStatementRequest { statements = myBatchStatementList } ddb.batchExecuteStatement(batchRequest) println("Deleted three movies using a batch command.") } suspend fun deleteTablePartiQLBatch(tableNameVal: String) { val request = DeleteTableRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.deleteTable(request) println("$tableNameVal was deleted") } }

Contoh kode berikut ini menunjukkan cara:

  • Dapatkan item dengan menjalankan SELECT pernyataan.

  • Tambahkan item dengan menjalankan INSERT pernyataan.

  • Perbarui item dengan menjalankan UPDATE pernyataan.

  • Hapus item dengan menjalankan DELETE pernyataan.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun main(args: Array<String>) { val usage = """ Usage: <fileName> Where: fileName - The path to the moviedata.json file You can download from the Amazon DynamoDB Developer Guide. """ if (args.size != 1) { println(usage) exitProcess(1) } val ddb = DynamoDbClient { region = "us-east-1" } val tableName = "MoviesPartiQ" // Get the moviedata.json from the Amazon DynamoDB Developer Guide. val fileName = args[0] println("Creating an Amazon DynamoDB table named MoviesPartiQ with a key named id and a sort key named title.") createTablePartiQL(ddb, tableName, "year") loadDataPartiQL(ddb, fileName) println("******* Getting data from the MoviesPartiQ table.") getMoviePartiQL(ddb) println("******* Putting a record into the MoviesPartiQ table.") putRecordPartiQL(ddb) println("******* Updating a record.") updateTableItemPartiQL(ddb) println("******* Querying the movies released in 2013.") queryTablePartiQL(ddb) println("******* Deleting the MoviesPartiQ table.") deleteTablePartiQL(tableName) } suspend fun createTablePartiQL( ddb: DynamoDbClient, tableNameVal: String, key: String, ) { val attDef = AttributeDefinition { attributeName = key attributeType = ScalarAttributeType.N } val attDef1 = AttributeDefinition { attributeName = "title" attributeType = ScalarAttributeType.S } val keySchemaVal = KeySchemaElement { attributeName = key keyType = KeyType.Hash } val keySchemaVal1 = KeySchemaElement { attributeName = "title" keyType = KeyType.Range } val provisionedVal = ProvisionedThroughput { readCapacityUnits = 10 writeCapacityUnits = 10 } val request = CreateTableRequest { attributeDefinitions = listOf(attDef, attDef1) keySchema = listOf(keySchemaVal, keySchemaVal1) provisionedThroughput = provisionedVal tableName = tableNameVal } val response = ddb.createTable(request) ddb.waitUntilTableExists { // suspend call tableName = tableNameVal } println("The table was successfully created ${response.tableDescription?.tableArn}") } suspend fun loadDataPartiQL( ddb: DynamoDbClient, fileName: String, ) { val sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}" val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val iter: Iterator<JsonNode> = rootNode.iterator() var currentNode: ObjectNode var t = 0 while (iter.hasNext()) { if (t == 200) { break } currentNode = iter.next() as ObjectNode val year = currentNode.path("year").asInt() val title = currentNode.path("title").asText() val info = currentNode.path("info").toString() val parameters: MutableList<AttributeValue> = ArrayList<AttributeValue>() parameters.add(AttributeValue.N(year.toString())) parameters.add(AttributeValue.S(title)) parameters.add(AttributeValue.S(info)) executeStatementPartiQL(ddb, sqlStatement, parameters) println("Added Movie $title") parameters.clear() t++ } } suspend fun getMoviePartiQL(ddb: DynamoDbClient) { val sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?" val parameters: MutableList<AttributeValue> = ArrayList<AttributeValue>() parameters.add(AttributeValue.N("2012")) parameters.add(AttributeValue.S("The Perks of Being a Wallflower")) val response = executeStatementPartiQL(ddb, sqlStatement, parameters) println("ExecuteStatement successful: $response") } suspend fun putRecordPartiQL(ddb: DynamoDbClient) { val sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}" val parameters: MutableList<AttributeValue> = java.util.ArrayList() parameters.add(AttributeValue.N("2020")) parameters.add(AttributeValue.S("My Movie")) parameters.add(AttributeValue.S("No Info")) executeStatementPartiQL(ddb, sqlStatement, parameters) println("Added new movie.") } suspend fun updateTableItemPartiQL(ddb: DynamoDbClient) { val sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\' where year=? and title=?" val parameters: MutableList<AttributeValue> = java.util.ArrayList() parameters.add(AttributeValue.N("2013")) parameters.add(AttributeValue.S("The East")) executeStatementPartiQL(ddb, sqlStatement, parameters) println("Item was updated!") } // Query the table where the year is 2013. suspend fun queryTablePartiQL(ddb: DynamoDbClient) { val sqlStatement = "SELECT * FROM MoviesPartiQ where year = ?" val parameters: MutableList<AttributeValue> = java.util.ArrayList() parameters.add(AttributeValue.N("2013")) val response = executeStatementPartiQL(ddb, sqlStatement, parameters) println("ExecuteStatement successful: $response") } suspend fun deleteTablePartiQL(tableNameVal: String) { val request = DeleteTableRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.deleteTable(request) println("$tableNameVal was deleted") } } suspend fun executeStatementPartiQL( ddb: DynamoDbClient, statementVal: String, parametersVal: List<AttributeValue>, ): ExecuteStatementResponse { val request = ExecuteStatementRequest { statement = statementVal parameters = parametersVal } return ddb.executeStatement(request) }