Mise en route avec PartiQL pour DynamoDB - Amazon DynamoDB

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.

Mise en route avec PartiQL pour DynamoDB

Cette section décrit comment utiliser PartiQL pour DynamoDB à partir de la console Amazon DynamoDB, de l'AWS Command Line Interface (AWS CLI) et des API DynamoDB.

Dans les exemples suivants, la table DynamoDB définie dans le didacticiel Mise en route avec DynamoDB est un prérequis.

Pour plus d'informations sur l'utilisation de la console DynamoDB, de l'AWS Command Line Interface ou des API DynamoDB pour accéder à DynamoDB, consultez Accès à DynamoDB.

Pour télécharger et utiliser le NoSQL Workbench afin de créer des instructions PartiQL pour DynamoDB, choisissez PartiQL operations (Opérations PartiQL) dans l'angle supérieur droit du NoSQL Workbench pour DynamoDB Operation Builder (Créateur d'opérations).

Console
Note

PartiQL pour DynamoDB n'est disponible que dans la nouvelle console DynamoDB. Pour utiliser la nouvelle console DynamoDB, dans le panneau de navigation sur le côté gauche de la console, choisissez Try the Preview of the new console (Essayer la version préliminaire de la nouvelle console).

  1. Connectez-vous à l'AWS Management Console et ouvrez la console DynamoDB à l'adresse https://console.aws.amazon.com/dynamodb/.

  2. Dans le panneau de navigation sur le côté gauche de la console, choisissez PartiQL editor (Editeur PartiQL).

  3. Choisissez la table Music.

  4. Choisissez Query table (Table de requête). Cette action génère une requête qui n'entraîne pas d'analyse de table complète.

  5. Remplacez partitionKeyValue par la valeur de chaîne Acme Band. Remplacez sortKeyValue par la valeur de chaîne Happy Day.

  6. Choisissez le bouton Run (Exécuter).

  7. Vous pouvez afficher les résultats de la requête en choisissant les boutons Table view (Vue tableau) ou JSON view (Vue JSON).

NoSQL workbench
  1. Choisissez PartiQL statement (Instruction PartiQL).

  2. Entrez l'instruction PartiQL SELECT suivante

    SELECT * FROM Music WHERE Artist=? and SongTitle=?
  3. Pour spécifier une valeur pour les paramètres Artist et SongTitle :

    1. Choisissez Optional request parameters (Paramètres de demande facultatifs).

    2. Choisissez Add new parameters (Ajouter de nouveaux paramètres).

    3. Choisissez le type d'attribut string (chaîne) et la valeur Acme Band.

    4. Répétez les étapes b et c, puis choisissez le type string (chaîne) et la valeur PartiQL Rocks.

  4. Si vous souhaitez générer un code, choisissez Generate code (Générer un code).

    Sélectionnez votre langage souhaité dans les onglets affichés. Vous pouvez désormais copier ce code et l'utiliser dans votre application.

  5. Si vous souhaitez que l'opération soit exécutée immédiatement, choisissez Run (Exécuter).

AWS CLI
  1. Créez un élément dans la table Music à l'aide de l'instruction INSERT PartiQL.

    aws dynamodb execute-statement --statement "INSERT INTO Music \ VALUE \ {'Artist':'Acme Band','SongTitle':'PartiQL Rocks'}"
  2. Extrayez un élément de la table Music à l'aide de l'instruction SELECT PartiQL.

    aws dynamodb execute-statement --statement "SELECT * FROM Music \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"
  3. Créez un élément dans la table Music à l'aide de l'instruction UPDATE PartiQL.

    aws dynamodb execute-statement --statement "UPDATE Music \ SET AwardsWon=1 \ SET AwardDetail={'Grammys':[2020, 2018]} \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"

    Ajoutez une valeur de liste pour un élément dans la table Music.

    aws dynamodb execute-statement --statement "UPDATE Music \ SET AwardDetail.Grammys =list_append(AwardDetail.Grammys,[2016]) \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"

    Supprimez une valeur de liste pour un élément dans la table Music.

    aws dynamodb execute-statement --statement "UPDATE Music \ REMOVE AwardDetail.Grammys[2] \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"

    Ajoutez un nouveau membre de mappage pour un élément dans la table Music.

    aws dynamodb execute-statement --statement "UPDATE Music \ SET AwardDetail.BillBoard=[2020] \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"

    Ajoutez un nouvel attribut d'ensemble de chaînes pour un élément dans la table Music.

    aws dynamodb execute-statement --statement "UPDATE Music \ SET BandMembers =<<'member1', 'member2'>> \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"

    Mettez à jour un attribut d'ensemble de chaînes pour un élément dans la table Music.

    aws dynamodb execute-statement --statement "UPDATE Music \ SET BandMembers =set_add(BandMembers, <<'newmember'>>) \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"
  4. Supprimez un élément de la table Music à l'aide de l'instruction PartiQL DELETE.

    aws dynamodb execute-statement --statement "DELETE FROM Music \ WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks'"
Java
import java.util.ArrayList; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.ExecuteStatementRequest; import com.amazonaws.services.dynamodbv2.model.ExecuteStatementResult; import com.amazonaws.services.dynamodbv2.model.InternalServerErrorException; import com.amazonaws.services.dynamodbv2.model.ItemCollectionSizeLimitExceededException; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughputExceededException; import com.amazonaws.services.dynamodbv2.model.RequestLimitExceededException; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import com.amazonaws.services.dynamodbv2.model.TransactionConflictException; public class DynamoDBPartiQGettingStarted { public static void main(String[] args) { // Create the DynamoDB Client with the region you want AmazonDynamoDB dynamoDB = createDynamoDbClient("us-west-1"); try { // Create ExecuteStatementRequest ExecuteStatementRequest executeStatementRequest = new ExecuteStatementRequest(); List<AttributeValue> parameters= getPartiQLParameters(); //Create an item in the Music table using the INSERT PartiQL statement processResults(executeStatementRequest(dynamoDB, "INSERT INTO Music value {'Artist':?,'SongTitle':?}", parameters)); //Retrieve an item from the Music table using the SELECT PartiQL statement. processResults(executeStatementRequest(dynamoDB, "SELECT * FROM Music where Artist=? and SongTitle=?", parameters)); //Update an item in the Music table using the UPDATE PartiQL statement. processResults(executeStatementRequest(dynamoDB, "UPDATE Music SET AwardsWon=1 SET AwardDetail={'Grammys':[2020, 2018]} where Artist=? and SongTitle=?", parameters)); //Add a list value for an item in the Music table. processResults(executeStatementRequest(dynamoDB, "UPDATE Music SET AwardDetail.Grammys =list_append(AwardDetail.Grammys,[2016]) where Artist=? and SongTitle=?", parameters)); //Remove a list value for an item in the Music table. processResults(executeStatementRequest(dynamoDB, "UPDATE Music REMOVE AwardDetail.Grammys[2] where Artist=? and SongTitle=?", parameters)); //Add a new map member for an item in the Music table. processResults(executeStatementRequest(dynamoDB, "UPDATE Music set AwardDetail.BillBoard=[2020] where Artist=? and SongTitle=?", parameters)); //Add a new string set attribute for an item in the Music table. processResults(executeStatementRequest(dynamoDB, "UPDATE Music SET BandMembers =<<'member1', 'member2'>> where Artist=? and SongTitle=?", parameters)); //update a string set attribute for an item in the Music table. processResults(executeStatementRequest(dynamoDB, "UPDATE Music SET BandMembers =set_add(BandMembers, <<'newmember'>>) where Artist=? and SongTitle=?", parameters)); //Retrieve an item from the Music table using the SELECT PartiQL statement. processResults(executeStatementRequest(dynamoDB, "SELECT * FROM Music where Artist=? and SongTitle=?", parameters)); //delete an item from the Music Table processResults(executeStatementRequest(dynamoDB, "DELETE FROM Music where Artist=? and SongTitle=?", parameters)); } catch (Exception e) { handleExecuteStatementErrors(e); } } private static AmazonDynamoDB createDynamoDbClient(String region) { return AmazonDynamoDBClientBuilder.standard().withRegion(region).build(); } private static List<AttributeValue> getPartiQLParameters() { List<AttributeValue> parameters = new ArrayList<AttributeValue>(); parameters.add(new AttributeValue("Acme Band")); parameters.add(new AttributeValue("PartiQL Rocks")); return parameters; } private static ExecuteStatementResult executeStatementRequest(AmazonDynamoDB client, String statement, List<AttributeValue> parameters ) { ExecuteStatementRequest request = new ExecuteStatementRequest(); request.setStatement(statement); request.setParameters(parameters); return client.executeStatement(request); } private static void processResults(ExecuteStatementResult executeStatementResult) { System.out.println("ExecuteStatement successful: "+ executeStatementResult.toString()); } // Handles errors during ExecuteStatement execution. Use recommendations in error messages below to add error handling specific to // your application use-case. private static void handleExecuteStatementErrors(Exception exception) { try { throw exception; } catch (ConditionalCheckFailedException ccfe) { System.out.println("Condition check specified in the operation failed, review and update the condition " + "check before retrying. Error: " + ccfe.getErrorMessage()); } catch (TransactionConflictException tce) { System.out.println("Operation was rejected because there is an ongoing transaction for the item, generally " + "safe to retry with exponential back-off. Error: " + tce.getErrorMessage()); } catch (ItemCollectionSizeLimitExceededException icslee) { System.out.println("An item collection is too large, you\'re using Local Secondary Index and exceeded " + "size limit of items per partition key. Consider using Global Secondary Index instead. Error: " + icslee.getErrorMessage()); } catch (Exception e) { handleCommonErrors(e); } } private static void handleCommonErrors(Exception exception) { try { throw exception; } catch (InternalServerErrorException isee) { System.out.println("Internal Server Error, generally safe to retry with exponential back-off. Error: " + isee.getErrorMessage()); } catch (RequestLimitExceededException rlee) { System.out.println("Throughput exceeds the current throughput limit for your account, increase account level throughput before " + "retrying. Error: " + rlee.getErrorMessage()); } catch (ProvisionedThroughputExceededException ptee) { System.out.println("Request rate is too high. If you're using a custom retry strategy make sure to retry with exponential back-off. " + "Otherwise consider reducing frequency of requests or increasing provisioned capacity for your table or secondary index. Error: " + ptee.getErrorMessage()); } catch (ResourceNotFoundException rnfe) { System.out.println("One of the tables was not found, verify table exists before retrying. Error: " + rnfe.getErrorMessage()); } catch (AmazonServiceException ase) { System.out.println("An AmazonServiceException occurred, indicates that the request was correctly transmitted to the DynamoDB " + "service, but for some reason, the service was not able to process it, and returned an error response instead. Investigate and " + "configure retry strategy. Error type: " + ase.getErrorType() + ". Error message: " + ase.getErrorMessage()); } catch (AmazonClientException ace) { System.out.println("An AmazonClientException occurred, indicates that the client was unable to get a response from DynamoDB " + "service, or the client was unable to parse the response from the service. Investigate and configure retry strategy. "+ "Error: " + ace.getMessage()); } catch (Exception e) { System.out.println("An exception occurred, investigate and configure retry strategy. Error: " + e.getMessage()); } } }