Exemples d'utilisation de DynamoDB pour Kotlin SDK - Exemples de code de l'AWS SDK

D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Exemples d'utilisation de DynamoDB pour Kotlin SDK

Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants en utilisant le AWS SDK pour Kotlin avec DynamoDB.

Les principes de base sont des exemples de code qui vous montrent comment effectuer les opérations essentielles au sein d'un service.

Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Les actions vous indiquent comment appeler des fonctions de service individuelles, mais vous pouvez les visualiser dans leur contexte dans les scénarios correspondants.

Les scénarios sont des exemples de code qui vous montrent comment accomplir des tâches spécifiques en appelant plusieurs fonctions au sein d'un service ou en les combinant à d'autres Services AWS.

Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.

Principes de base

L’exemple de code suivant illustre comment :

  • Créez une table pouvant contenir des données vidéo.

  • Insérer, récupérez et mettez à jour un seul film dans la table.

  • Écrivez les données du film dans le tableau à partir d'un JSON fichier d'exemple.

  • Recherchez les films sortis au cours d'une année donnée.

  • Recherchez les films sortis au cours d'une plage d'années spécifique.

  • Supprimez un film de la table, puis supprimez la table.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Créez une table 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}") } }

Créez une fonction d'assistance pour télécharger et extraire le JSON fichier d'exemple.

// 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.") } }

Obtenez un élément d'une 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) } } }

Exemple complet.

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]}") } } } }

Actions

L'exemple de code suivant montre comment utiliserCreateTable.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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 } }
  • Pour API plus de détails, voir CreateTablela APIréférence AWS SDK à Kotlin.

L'exemple de code suivant montre comment utiliserDeleteItem.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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") } }
  • Pour API plus de détails, voir DeleteItemla APIréférence AWS SDK à Kotlin.

L'exemple de code suivant montre comment utiliserDeleteTable.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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") } }
  • Pour API plus de détails, voir DeleteTablela APIréférence AWS SDK à Kotlin.

L'exemple de code suivant montre comment utiliserGetItem.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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) } } }
  • Pour API plus de détails, voir GetItemla APIréférence AWS SDK à Kotlin.

L'exemple de code suivant montre comment utiliserListTables.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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") } } }
  • Pour API plus de détails, voir ListTablesla APIréférence AWS SDK à Kotlin.

L'exemple de code suivant montre comment utiliserPutItem.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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.") } }
  • Pour API plus de détails, voir PutItemla APIréférence AWS SDK à Kotlin.

L'exemple de code suivant montre comment utiliserQuery.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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 } }
  • Pour API plus de détails, voir Query in AWS SDKfor Kotlin API reference.

L'exemple de code suivant montre comment utiliserScan.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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]}") } } } }
  • Pour API plus de détails, voir Scan in AWS SDKfor Kotlin API reference.

L'exemple de code suivant montre comment utiliserUpdateItem.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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") } }
  • Pour API plus de détails, voir UpdateItemla APIréférence AWS SDK à Kotlin.

Scénarios

L'exemple de code suivant montre comment créer une application qui envoie des données à une table Amazon DynamoDB et vous avertit lorsqu'un utilisateur met à jour la table.

SDKpour Kotlin

Montre comment créer une application Android native qui envoie des données à l'aide d'Amazon DynamoDB API Kotlin et envoie un message texte à l'aide d'Amazon Kotlin. SNS API

Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Les services utilisés dans cet exemple
  • DynamoDB

  • Amazon SNS

L'exemple de code suivant montre comment créer une application sans serveur permettant aux utilisateurs de gérer des photos à l'aide d'étiquettes.

SDKpour Kotlin

Montre comment développer une application de gestion de ressources photographiques qui détecte les étiquettes dans les images à l’aide d’Amazon Rekognition et les stocke pour les récupérer ultérieurement.

Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Pour explorer en profondeur l’origine de cet exemple, consultez l’article sur AWS  Community.

Les services utilisés dans cet exemple
  • APIPasserelle

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

L'exemple de code suivant montre comment créer une application Web qui suit les éléments de travail dans une table Amazon DynamoDB et utilise Amazon Simple Email Service (SESAmazon) pour envoyer des rapports.

SDKpour Kotlin

Montre comment utiliser Amazon API DynamoDB pour créer une application Web dynamique qui suit les données de travail DynamoDB.

Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Les services utilisés dans cet exemple
  • DynamoDB

  • Amazon SES

L’exemple de code suivant illustre comment :

  • Obtenez un lot d'éléments en exécutant plusieurs SELECT instructions.

  • Ajoutez un lot d'éléments en exécutant plusieurs INSERT instructions.

  • Mettez à jour un lot d'éléments en exécutant plusieurs UPDATE instructions.

  • Supprimez un lot d'éléments en exécutant plusieurs DELETE instructions.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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") } }

L’exemple de code suivant illustre comment :

  • Obtenez un objet en exécutant une SELECT déclaration.

  • Ajoutez un élément en exécutant une INSERT instruction.

  • Mettez à jour un élément en exécutant une UPDATE instruction.

  • Supprimez un élément en exécutant une DELETE instruction.

SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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) }
  • Pour API plus de détails, voir ExecuteStatementla APIréférence AWS SDK à Kotlin.