Ausführen von Transaktionen mit PartiQL für DynamoDB - Amazon-DynamoDB

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Ausführen von Transaktionen mit PartiQL für DynamoDB

In diesem Abschnitt wird die Verwendung von Transaktionen mit PartiQL für DynamoDB beschrieben. PartiQL-Transaktionen sind auf insgesamt 100 Anweisungen (Aktionen) begrenzt.

Weitere Informationen zu DynamoDB-Transaktionen finden Sie unter Verwalten komplexer Workflows mit DynamoDB-Transaktionen.

Anmerkung

Die gesamte Transaktion muss entweder aus Leseanweisungen oder Schreibanweisungen bestehen. Sie können nicht beides in einer Transaktion mischen. Die EXISTS-Funktion ist eine Ausnahme. Sie können sie verwenden, um den Zustand bestimmter Attribute des Elements auf ähnliche Weise wie ConditionCheck bei der TransactWriteElement-API-Operation zu überprüfen.

Syntax

[ { "Statement":" statement ", "Parameters":[ { " parametertype " : " parametervalue " }, ...] } , ... ]

Parameter

statement

(Erforderlich) Eine unterstützte PartiQL für DynamoDB-Anweisung.

Anmerkung

Die gesamte Transaktion muss entweder aus Leseanweisungen oder Schreibanweisungen bestehen. Sie können nicht beides in einer Transaktion mischen.

parametertype

(Optional) Ein DynamoDB-Typ, wenn Parameter bei der Angabe der PartiQL-Anweisung verwendet wurden.

parametervalue

(Optional) Ein Parameterwert, wenn Parameter bei der Angabe der PartiQL-Anweisung verwendet wurden.

Rückgabewerte

Diese Anweisung gibt keine Werte für Schreibvorgänge (INSERT, UPDATE oder DELETE) zurück. Sie gibt jedoch verschiedene Werte für Lesevorgänge (SELECT) basierend auf den in der WHERE-Klausel angegebenen Bedingungen zurück.

Anmerkung

Wenn eine der Singleton-Operationen INSERT, UPDATE oder DELETE einen Fehler zurückgibt, werden die Transaktionen mit einer TransactionCanceledException-Ausnahme abgebrochen, und der Code für den Abbruchgrund enthält die Fehler der einzelnen Singleton-Operationen.

Beispiele

Im folgenden Beispiel werden mehrere Anweisungen als Transaktion ausgeführt.

AWS CLI
  1. Speichern Sie den folgenden JSON-Code in einer Datei mit dem Namen partiql.json.

    [ { "Statement": "EXISTS(SELECT * FROM \"Music\" where Artist='No One You Know' and SongTitle='Call Me Today' and Awards is MISSING)" }, { "Statement": "INSERT INTO Music value {'Artist':?,'SongTitle':'?'}", "Parameters": [{\"S\": \"Acme Band\"}, {\"S\": \"Best Song\"}] }, { "Statement": "UPDATE \"Music\" SET AwardsWon=1 SET AwardDetail={'Grammys':[2020, 2018]} where Artist='Acme Band' and SongTitle='PartiQL Rocks'" } ]
  2. Führen Sie in der Eingabeaufforderung den folgenden Befehl aus.

    aws dynamodb execute-transaction --transact-statements file://partiql.json
Java
public class DynamoDBPartiqlTransaction { public static void main(String[] args) { // Create the DynamoDB Client with the region you want AmazonDynamoDB dynamoDB = createDynamoDbClient("us-west-2"); try { // Create ExecuteTransactionRequest ExecuteTransactionRequest executeTransactionRequest = createExecuteTransactionRequest(); ExecuteTransactionResult executeTransactionResult = dynamoDB.executeTransaction(executeTransactionRequest); System.out.println("ExecuteTransaction successful."); // Handle executeTransactionResult } catch (Exception e) { handleExecuteTransactionErrors(e); } } private static AmazonDynamoDB createDynamoDbClient(String region) { return AmazonDynamoDBClientBuilder.standard().withRegion(region).build(); } private static ExecuteTransactionRequest createExecuteTransactionRequest() { ExecuteTransactionRequest request = new ExecuteTransactionRequest(); // Create statements List<ParameterizedStatement> statements = getPartiQLTransactionStatements(); request.setTransactStatements(statements); return request; } private static List<ParameterizedStatement> getPartiQLTransactionStatements() { List<ParameterizedStatement> statements = new ArrayList<ParameterizedStatement>(); statements.add(new ParameterizedStatement() .withStatement("EXISTS(SELECT * FROM "Music" where Artist='No One You Know' and SongTitle='Call Me Today' and Awards is MISSING)")); statements.add(new ParameterizedStatement() .withStatement("INSERT INTO "Music" value {'Artist':'?','SongTitle':'?'}") .withParameters(new AttributeValue("Acme Band"),new AttributeValue("Best Song"))); statements.add(new ParameterizedStatement() .withStatement("UPDATE "Music" SET AwardsWon=1 SET AwardDetail={'Grammys':[2020, 2018]} where Artist='Acme Band' and SongTitle='PartiQL Rocks'")); return statements; } // Handles errors during ExecuteTransaction execution. Use recommendations in error messages below to add error handling specific to // your application use-case. private static void handleExecuteTransactionErrors(Exception exception) { try { throw exception; } catch (TransactionCanceledException tce) { System.out.println("Transaction Cancelled, implies a client issue, fix before retrying. Error: " + tce.getErrorMessage()); } catch (TransactionInProgressException tipe) { System.out.println("The transaction with the given request token is already in progress, consider changing " + "retry strategy for this type of error. Error: " + tipe.getErrorMessage()); } catch (IdempotentParameterMismatchException ipme) { System.out.println("Request rejected because it was retried with a different payload but with a request token that was already used, " + "change request token for this payload to be accepted. Error: " + ipme.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()); } } }

Das folgende Beispiel zeigt die verschiedenen Rückgabewerte, wenn DynamoDB-Elemente mit unterschiedlichen Bedingungen liest, die in der WHERE-Klausel angegeben sind.

AWS CLI
  1. Speichern Sie den folgenden JSON-Code in einer Datei mit dem Namen partiql.json.

    [ // Item exists and projected attribute exists { "Statement": "SELECT * FROM "Music" WHERE Artist='No One You Know' and SongTitle='Call Me Today'" }, // Item exists but projected attributes do not exist { "Statement": "SELECT non_existent_projected_attribute FROM "Music" WHERE Artist='No One You Know' and SongTitle='Call Me Today'" }, // Item does not exist { "Statement": "SELECT * FROM "Music" WHERE Artist='No One I Know' and SongTitle='Call You Today'" } ]
  2. Folgenden Befehl in der Eingabeaufforderung eingeben.

    aws dynamodb execute-transaction --transact-statements file://partiql.json
  3. Die folgende Antwort wird ausgegeben:

    { "Responses": [ // Item exists and projected attribute exists { "Item": { "Artist":{ "S": "No One You Know" }, "SongTitle":{ "S": "Call Me Today" } } }, // Item exists but projected attributes do not exist { "Item": {} }, // Item does not exist {} ] }