Exemples d'Amazon Keyspaces utilisant le SDK pour Java 2.x - AWS SDK for Java 2.x

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'Amazon Keyspaces utilisant le SDK pour Java 2.x

Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l' AWS SDK for Java 2.x aide d'Amazon Keyspaces.

Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Alors que les actions vous indiquent comment appeler des fonctions de service individuelles, vous pouvez les voir en contexte dans leurs scénarios associés et dans des exemples interservices.

Les Scénarios sont des exemples de code qui vous montrent comment accomplir une tâche spécifique en appelant plusieurs fonctions au sein d’un même service.

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

Mise en route

Les exemples de code suivants montrent comment commencer à utiliser Amazon Keyspaces.

SDK pour Java 2.x
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.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.keyspaces.KeyspacesClient; import software.amazon.awssdk.services.keyspaces.model.KeyspaceSummary; import software.amazon.awssdk.services.keyspaces.model.KeyspacesException; import software.amazon.awssdk.services.keyspaces.model.ListKeyspacesRequest; import software.amazon.awssdk.services.keyspaces.model.ListKeyspacesResponse; import java.util.List; /** * Before running this Java (v2) code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class HelloKeyspaces { public static void main(String[] args) { Region region = Region.US_EAST_1; KeyspacesClient keyClient = KeyspacesClient.builder() .region(region) .build(); listKeyspaces(keyClient); } public static void listKeyspaces(KeyspacesClient keyClient) { try { ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder() .maxResults(10) .build(); ListKeyspacesResponse response = keyClient.listKeyspaces(keyspacesRequest); List<KeyspaceSummary> keyspaces = response.keyspaces(); for (KeyspaceSummary keyspace : keyspaces) { System.out.println("The name of the keyspace is " + keyspace.keyspaceName()); } } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Pour plus de détails sur l'API, reportez-vous ListKeyspacesà la section Référence des AWS SDK for Java 2.x API.

Actions

L'exemple de code suivant montre comment utiliserCreateKeyspace.

SDK pour Java 2.x
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.

public static void createKeySpace(KeyspacesClient keyClient, String keyspaceName) { try { CreateKeyspaceRequest keyspaceRequest = CreateKeyspaceRequest.builder() .keyspaceName(keyspaceName) .build(); CreateKeyspaceResponse response = keyClient.createKeyspace(keyspaceRequest); System.out.println("The ARN of the KeySpace is " + response.resourceArn()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous CreateKeyspaceà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserCreateTable.

SDK pour Java 2.x
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.

public static void createTable(KeyspacesClient keyClient, String keySpace, String tableName) { try { // Set the columns. ColumnDefinition defTitle = ColumnDefinition.builder() .name("title") .type("text") .build(); ColumnDefinition defYear = ColumnDefinition.builder() .name("year") .type("int") .build(); ColumnDefinition defReleaseDate = ColumnDefinition.builder() .name("release_date") .type("timestamp") .build(); ColumnDefinition defPlot = ColumnDefinition.builder() .name("plot") .type("text") .build(); List<ColumnDefinition> colList = new ArrayList<>(); colList.add(defTitle); colList.add(defYear); colList.add(defReleaseDate); colList.add(defPlot); // Set the keys. PartitionKey yearKey = PartitionKey.builder() .name("year") .build(); PartitionKey titleKey = PartitionKey.builder() .name("title") .build(); List<PartitionKey> keyList = new ArrayList<>(); keyList.add(yearKey); keyList.add(titleKey); SchemaDefinition schemaDefinition = SchemaDefinition.builder() .partitionKeys(keyList) .allColumns(colList) .build(); PointInTimeRecovery timeRecovery = PointInTimeRecovery.builder() .status(PointInTimeRecoveryStatus.ENABLED) .build(); CreateTableRequest tableRequest = CreateTableRequest.builder() .keyspaceName(keySpace) .tableName(tableName) .schemaDefinition(schemaDefinition) .pointInTimeRecovery(timeRecovery) .build(); CreateTableResponse response = keyClient.createTable(tableRequest); System.out.println("The table ARN is " + response.resourceArn()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous CreateTableà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserDeleteKeyspace.

SDK pour Java 2.x
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.

public static void deleteKeyspace(KeyspacesClient keyClient, String keyspaceName) { try { DeleteKeyspaceRequest deleteKeyspaceRequest = DeleteKeyspaceRequest.builder() .keyspaceName(keyspaceName) .build(); keyClient.deleteKeyspace(deleteKeyspaceRequest); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous DeleteKeyspaceà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserDeleteTable.

SDK pour Java 2.x
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.

public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, String tableName) { try { DeleteTableRequest tableRequest = DeleteTableRequest.builder() .keyspaceName(keyspaceName) .tableName(tableName) .build(); keyClient.deleteTable(tableRequest); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous DeleteTableà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserGetKeyspace.

SDK pour Java 2.x
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.

public static void checkKeyspaceExistence(KeyspacesClient keyClient, String keyspaceName) { try { GetKeyspaceRequest keyspaceRequest = GetKeyspaceRequest.builder() .keyspaceName(keyspaceName) .build(); GetKeyspaceResponse response = keyClient.getKeyspace(keyspaceRequest); String name = response.keyspaceName(); System.out.println("The " + name + " KeySpace is ready"); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous GetKeyspaceà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserGetTable.

SDK pour Java 2.x
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.

public static void checkTable(KeyspacesClient keyClient, String keyspaceName, String tableName) throws InterruptedException { try { boolean tableStatus = false; String status; GetTableResponse response = null; GetTableRequest tableRequest = GetTableRequest.builder() .keyspaceName(keyspaceName) .tableName(tableName) .build(); while (!tableStatus) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); System.out.println(". The table status is " + status); if (status.compareTo("ACTIVE") == 0) { tableStatus = true; } Thread.sleep(500); } List<ColumnDefinition> cols = response.schemaDefinition().allColumns(); for (ColumnDefinition def : cols) { System.out.println("The column name is " + def.name()); System.out.println("The column type is " + def.type()); } } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous GetTableà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserListKeyspaces.

SDK pour Java 2.x
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.

public static void listKeyspacesPaginator(KeyspacesClient keyClient) { try { ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder() .maxResults(10) .build(); ListKeyspacesIterable listRes = keyClient.listKeyspacesPaginator(keyspacesRequest); listRes.stream() .flatMap(r -> r.keyspaces().stream()) .forEach(content -> System.out.println(" Name: " + content.keyspaceName())); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous ListKeyspacesà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserListTables.

SDK pour Java 2.x
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.

public static void listTables(KeyspacesClient keyClient, String keyspaceName) { try { ListTablesRequest tablesRequest = ListTablesRequest.builder() .keyspaceName(keyspaceName) .build(); ListTablesIterable listRes = keyClient.listTablesPaginator(tablesRequest); listRes.stream() .flatMap(r -> r.tables().stream()) .forEach(content -> System.out.println(" ARN: " + content.resourceArn() + " Table name: " + content.tableName())); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous ListTablesà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserRestoreTable.

SDK pour Java 2.x
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.

public static void restoreTable(KeyspacesClient keyClient, String keyspaceName, ZonedDateTime utc) { try { Instant myTime = utc.toInstant(); RestoreTableRequest restoreTableRequest = RestoreTableRequest.builder() .restoreTimestamp(myTime) .sourceTableName("Movie") .targetKeyspaceName(keyspaceName) .targetTableName("MovieRestore") .sourceKeyspaceName(keyspaceName) .build(); RestoreTableResponse response = keyClient.restoreTable(restoreTableRequest); System.out.println("The ARN of the restored table is " + response.restoredTableARN()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous RestoreTableà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserUpdateTable.

SDK pour Java 2.x
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.

public static void updateTable(KeyspacesClient keyClient, String keySpace, String tableName) { try { ColumnDefinition def = ColumnDefinition.builder() .name("watched") .type("boolean") .build(); UpdateTableRequest tableRequest = UpdateTableRequest.builder() .keyspaceName(keySpace) .tableName(tableName) .addColumns(def) .build(); keyClient.updateTable(tableRequest); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Pour plus de détails sur l'API, reportez-vous UpdateTableà la section Référence des AWS SDK for Java 2.x API.

Scénarios

L’exemple de code suivant illustre comment :

  • Créez un espace de touches et un tableau. Le schéma de table contient les données vidéo et la point-in-time restauration est activée.

  • Connectez-vous au keyspace à l'aide d'une connexion TLS sécurisée avec authentification SigV4.

  • Interrogez la table. Ajoutez, récupérez et mettez à jour les données des films.

  • Mettez à jour le tableau. Ajoutez une colonne pour suivre les films visionnés.

  • Restaurez l'état précédent de la table et nettoyez les ressources.

SDK pour Java 2.x
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.

/** * Before running this Java (v2) code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * Before running this Java code example, you must create a * Java keystore (JKS) file and place it in your project's resources folder. * * This file is a secure file format used to hold certificate information for * Java applications. This is required to make a connection to Amazon Keyspaces. * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/keyspaces/latest/devguide/using_java_driver.html * * This Java example performs the following tasks: * * 1. Create a keyspace. * 2. Check for keyspace existence. * 3. List keyspaces using a paginator. * 4. Create a table with a simple movie data schema and enable point-in-time * recovery. * 5. Check for the table to be in an Active state. * 6. List all tables in the keyspace. * 7. Use a Cassandra driver to insert some records into the Movie table. * 8. Get all records from the Movie table. * 9. Get a specific Movie. * 10. Get a UTC timestamp for the current time. * 11. Update the table schema to add a ‘watched’ Boolean column. * 12. Update an item as watched. * 13. Query for items with watched = True. * 14. Restore the table back to the previous state using the timestamp. * 15. Check for completion of the restore action. * 16. Delete the table. * 17. Confirm that both tables are deleted. * 18. Delete the keyspace. */ public class ScenarioKeyspaces { public static final String DASHES = new String(new char[80]).replace("\0", "-"); /* * Usage: * fileName - The name of the JSON file that contains movie data. (Get this file * from the GitHub repo at resources/sample_file.) * keyspaceName - The name of the keyspace to create. */ public static void main(String[] args) throws InterruptedException, IOException { String fileName = "<Replace with the JSON file that contains movie data>"; String keyspaceName = "<Replace with the name of the keyspace to create>"; String titleUpdate = "The Family"; int yearUpdate = 2013; String tableName = "Movie"; String tableNameRestore = "MovieRestore"; Region region = Region.US_EAST_1; KeyspacesClient keyClient = KeyspacesClient.builder() .region(region) .build(); DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf"); CqlSession session = CqlSession.builder() .withConfigLoader(loader) .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon Keyspaces example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("1. Create a keyspace."); createKeySpace(keyClient, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); Thread.sleep(5000); System.out.println("2. Check for keyspace existence."); checkKeyspaceExistence(keyClient, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. List keyspaces using a paginator."); listKeyspacesPaginator(keyClient); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Create a table with a simple movie data schema and enable point-in-time recovery."); createTable(keyClient, keyspaceName, tableName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Check for the table to be in an Active state."); Thread.sleep(6000); checkTable(keyClient, keyspaceName, tableName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. List all tables in the keyspace."); listTables(keyClient, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Use a Cassandra driver to insert some records into the Movie table."); Thread.sleep(6000); loadData(session, fileName, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("8. Get all records from the Movie table."); getMovieData(session, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("9. Get a specific Movie."); getSpecificMovie(session, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("10. Get a UTC timestamp for the current time."); ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); System.out.println("DATETIME = " + Date.from(utc.toInstant())); System.out.println(DASHES); System.out.println(DASHES); System.out.println("11. Update the table schema to add a watched Boolean column."); updateTable(keyClient, keyspaceName, tableName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("12. Update an item as watched."); Thread.sleep(10000); // Wait 10 secs for the update. updateRecord(session, keyspaceName, titleUpdate, yearUpdate); System.out.println(DASHES); System.out.println(DASHES); System.out.println("13. Query for items with watched = True."); getWatchedData(session, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("14. Restore the table back to the previous state using the timestamp."); System.out.println("Note that the restore operation can take up to 20 minutes."); restoreTable(keyClient, keyspaceName, utc); System.out.println(DASHES); System.out.println(DASHES); System.out.println("15. Check for completion of the restore action."); Thread.sleep(5000); checkRestoredTable(keyClient, keyspaceName, "MovieRestore"); System.out.println(DASHES); System.out.println(DASHES); System.out.println("16. Delete both tables."); deleteTable(keyClient, keyspaceName, tableName); deleteTable(keyClient, keyspaceName, tableNameRestore); System.out.println(DASHES); System.out.println(DASHES); System.out.println("17. Confirm that both tables are deleted."); checkTableDelete(keyClient, keyspaceName, tableName); checkTableDelete(keyClient, keyspaceName, tableNameRestore); System.out.println(DASHES); System.out.println(DASHES); System.out.println("18. Delete the keyspace."); deleteKeyspace(keyClient, keyspaceName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("The scenario has completed successfully."); System.out.println(DASHES); } public static void deleteKeyspace(KeyspacesClient keyClient, String keyspaceName) { try { DeleteKeyspaceRequest deleteKeyspaceRequest = DeleteKeyspaceRequest.builder() .keyspaceName(keyspaceName) .build(); keyClient.deleteKeyspace(deleteKeyspaceRequest); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void checkTableDelete(KeyspacesClient keyClient, String keyspaceName, String tableName) throws InterruptedException { try { String status; GetTableResponse response; GetTableRequest tableRequest = GetTableRequest.builder() .keyspaceName(keyspaceName) .tableName(tableName) .build(); // Keep looping until table cannot be found and a ResourceNotFoundException is // thrown. while (true) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); System.out.println(". The table status is " + status); Thread.sleep(500); } } catch (ResourceNotFoundException e) { System.err.println(e.awsErrorDetails().errorMessage()); } System.out.println("The table is deleted"); } public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, String tableName) { try { DeleteTableRequest tableRequest = DeleteTableRequest.builder() .keyspaceName(keyspaceName) .tableName(tableName) .build(); keyClient.deleteTable(tableRequest); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void checkRestoredTable(KeyspacesClient keyClient, String keyspaceName, String tableName) throws InterruptedException { try { boolean tableStatus = false; String status; GetTableResponse response = null; GetTableRequest tableRequest = GetTableRequest.builder() .keyspaceName(keyspaceName) .tableName(tableName) .build(); while (!tableStatus) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); System.out.println("The table status is " + status); if (status.compareTo("ACTIVE") == 0) { tableStatus = true; } Thread.sleep(500); } List<ColumnDefinition> cols = response.schemaDefinition().allColumns(); for (ColumnDefinition def : cols) { System.out.println("The column name is " + def.name()); System.out.println("The column type is " + def.type()); } } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void restoreTable(KeyspacesClient keyClient, String keyspaceName, ZonedDateTime utc) { try { Instant myTime = utc.toInstant(); RestoreTableRequest restoreTableRequest = RestoreTableRequest.builder() .restoreTimestamp(myTime) .sourceTableName("Movie") .targetKeyspaceName(keyspaceName) .targetTableName("MovieRestore") .sourceKeyspaceName(keyspaceName) .build(); RestoreTableResponse response = keyClient.restoreTable(restoreTableRequest); System.out.println("The ARN of the restored table is " + response.restoredTableARN()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void getWatchedData(CqlSession session, String keyspaceName) { ResultSet resultSet = session .execute("SELECT * FROM \"" + keyspaceName + "\".\"Movie\" WHERE watched = true ALLOW FILTERING;"); resultSet.forEach(item -> { System.out.println("The Movie title is " + item.getString("title")); System.out.println("The Movie year is " + item.getInt("year")); System.out.println("The plot is " + item.getString("plot")); }); } public static void updateRecord(CqlSession session, String keySpace, String titleUpdate, int yearUpdate) { String sqlStatement = "UPDATE \"" + keySpace + "\".\"Movie\" SET watched=true WHERE title = :k0 AND year = :k1;"; BatchStatementBuilder builder = BatchStatement.builder(DefaultBatchType.UNLOGGED); builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); PreparedStatement preparedStatement = session.prepare(sqlStatement); builder.addStatement(preparedStatement.boundStatementBuilder() .setString("k0", titleUpdate) .setInt("k1", yearUpdate) .build()); BatchStatement batchStatement = builder.build(); session.execute(batchStatement); } public static void updateTable(KeyspacesClient keyClient, String keySpace, String tableName) { try { ColumnDefinition def = ColumnDefinition.builder() .name("watched") .type("boolean") .build(); UpdateTableRequest tableRequest = UpdateTableRequest.builder() .keyspaceName(keySpace) .tableName(tableName) .addColumns(def) .build(); keyClient.updateTable(tableRequest); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void getSpecificMovie(CqlSession session, String keyspaceName) { ResultSet resultSet = session.execute( "SELECT * FROM \"" + keyspaceName + "\".\"Movie\" WHERE title = 'The Family' ALLOW FILTERING ;"); resultSet.forEach(item -> { System.out.println("The Movie title is " + item.getString("title")); System.out.println("The Movie year is " + item.getInt("year")); System.out.println("The plot is " + item.getString("plot")); }); } // Get records from the Movie table. public static void getMovieData(CqlSession session, String keyspaceName) { ResultSet resultSet = session.execute("SELECT * FROM \"" + keyspaceName + "\".\"Movie\";"); resultSet.forEach(item -> { System.out.println("The Movie title is " + item.getString("title")); System.out.println("The Movie year is " + item.getInt("year")); System.out.println("The plot is " + item.getString("plot")); }); } // Load data into the table. public static void loadData(CqlSession session, String fileName, String keySpace) throws IOException { String sqlStatement = "INSERT INTO \"" + keySpace + "\".\"Movie\" (title, year, plot) values (:k0, :k1, :k2)"; JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); ObjectNode currentNode; int t = 0; while (iter.hasNext()) { // Add 20 movies to the table. if (t == 20) break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); String title = currentNode.path("title").asText(); String plot = currentNode.path("info").path("plot").toString(); // Insert the data into the Amazon Keyspaces table. BatchStatementBuilder builder = BatchStatement.builder(DefaultBatchType.UNLOGGED); builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); PreparedStatement preparedStatement = session.prepare(sqlStatement); builder.addStatement(preparedStatement.boundStatementBuilder() .setString("k0", title) .setInt("k1", year) .setString("k2", plot) .build()); BatchStatement batchStatement = builder.build(); session.execute(batchStatement); t++; } System.out.println("You have added " + t + " records successfully!"); } public static void listTables(KeyspacesClient keyClient, String keyspaceName) { try { ListTablesRequest tablesRequest = ListTablesRequest.builder() .keyspaceName(keyspaceName) .build(); ListTablesIterable listRes = keyClient.listTablesPaginator(tablesRequest); listRes.stream() .flatMap(r -> r.tables().stream()) .forEach(content -> System.out.println(" ARN: " + content.resourceArn() + " Table name: " + content.tableName())); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void checkTable(KeyspacesClient keyClient, String keyspaceName, String tableName) throws InterruptedException { try { boolean tableStatus = false; String status; GetTableResponse response = null; GetTableRequest tableRequest = GetTableRequest.builder() .keyspaceName(keyspaceName) .tableName(tableName) .build(); while (!tableStatus) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); System.out.println(". The table status is " + status); if (status.compareTo("ACTIVE") == 0) { tableStatus = true; } Thread.sleep(500); } List<ColumnDefinition> cols = response.schemaDefinition().allColumns(); for (ColumnDefinition def : cols) { System.out.println("The column name is " + def.name()); System.out.println("The column type is " + def.type()); } } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void createTable(KeyspacesClient keyClient, String keySpace, String tableName) { try { // Set the columns. ColumnDefinition defTitle = ColumnDefinition.builder() .name("title") .type("text") .build(); ColumnDefinition defYear = ColumnDefinition.builder() .name("year") .type("int") .build(); ColumnDefinition defReleaseDate = ColumnDefinition.builder() .name("release_date") .type("timestamp") .build(); ColumnDefinition defPlot = ColumnDefinition.builder() .name("plot") .type("text") .build(); List<ColumnDefinition> colList = new ArrayList<>(); colList.add(defTitle); colList.add(defYear); colList.add(defReleaseDate); colList.add(defPlot); // Set the keys. PartitionKey yearKey = PartitionKey.builder() .name("year") .build(); PartitionKey titleKey = PartitionKey.builder() .name("title") .build(); List<PartitionKey> keyList = new ArrayList<>(); keyList.add(yearKey); keyList.add(titleKey); SchemaDefinition schemaDefinition = SchemaDefinition.builder() .partitionKeys(keyList) .allColumns(colList) .build(); PointInTimeRecovery timeRecovery = PointInTimeRecovery.builder() .status(PointInTimeRecoveryStatus.ENABLED) .build(); CreateTableRequest tableRequest = CreateTableRequest.builder() .keyspaceName(keySpace) .tableName(tableName) .schemaDefinition(schemaDefinition) .pointInTimeRecovery(timeRecovery) .build(); CreateTableResponse response = keyClient.createTable(tableRequest); System.out.println("The table ARN is " + response.resourceArn()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void listKeyspacesPaginator(KeyspacesClient keyClient) { try { ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder() .maxResults(10) .build(); ListKeyspacesIterable listRes = keyClient.listKeyspacesPaginator(keyspacesRequest); listRes.stream() .flatMap(r -> r.keyspaces().stream()) .forEach(content -> System.out.println(" Name: " + content.keyspaceName())); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void checkKeyspaceExistence(KeyspacesClient keyClient, String keyspaceName) { try { GetKeyspaceRequest keyspaceRequest = GetKeyspaceRequest.builder() .keyspaceName(keyspaceName) .build(); GetKeyspaceResponse response = keyClient.getKeyspace(keyspaceRequest); String name = response.keyspaceName(); System.out.println("The " + name + " KeySpace is ready"); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void createKeySpace(KeyspacesClient keyClient, String keyspaceName) { try { CreateKeyspaceRequest keyspaceRequest = CreateKeyspaceRequest.builder() .keyspaceName(keyspaceName) .build(); CreateKeyspaceResponse response = keyClient.createKeyspace(keyspaceRequest); System.out.println("The ARN of the KeySpace is " + response.resourceArn()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }