Driver Amazon QLDB per .NET — Riferimento al ricettario - Database Amazon Quantum Ledger (Amazon QLDB)

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Driver Amazon QLDB per .NET — Riferimento al ricettario

Questa guida di riferimento mostra i casi d'uso più comuni del driver Amazon QLDB per .NET. Fornisce esempi di codice C# che illustra come utilizzare il driver per eseguire operazioni di creazione, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, lettura, aggiornamento ed eliminazione (CRUD) Include anche esempi di codice per l'elaborazione dei dati di Amazon Ion. Inoltre, questa guida evidenzia le migliori pratiche per rendere le transazioni idempotenti e implementare i vincoli di unicità.

Nota

Questo argomento fornisce esempi di codice di elaborazione dei dati Amazon Ion utilizzando la mappatrice di oggetti Ion per impostazione predefinita. QLDB ha introdotto il mappatore di oggetti Ion nella versione 1.3.0 del driver.NET. Ove applicabile, questo argomento fornisce anche esempi di codice che utilizzano la libreria Ion standard come alternativa. Per ulteriori informazioni, consulta Uso di Amazon Ion.

Importazione del driver

Il seguente esempio di codice importa il driver.

using Amazon.QLDB.Driver; using Amazon.QLDB.Driver.Generic; using Amazon.QLDB.Driver.Serialization;
using Amazon.QLDB.Driver; using Amazon.IonDotnet.Builders;

Istanziazione del driver

L'esempio di codice seguente crea un'istanza del driver che si connette a un nome di registro specificato utilizzando le impostazioni predefinite.

Async
IAsyncQldbDriver driver = AsyncQldbDriver.Builder() .WithLedger("vehicle-registration") // Add Serialization library .WithSerializer(new ObjectSerializer()) .Build();
Sync
IQldbDriver driver = QldbDriver.Builder() .WithLedger("vehicle-registration") // Add Serialization library .WithSerializer(new ObjectSerializer()) .Build();
Async
IAsyncQldbDriver driver = AsyncQldbDriver.Builder().WithLedger("vehicle-registration").Build();
Sync
IQldbDriver driver = QldbDriver.Builder().WithLedger("vehicle-registration").Build();

Operazioni CRUD

QLDB esegue operazioni di creazione, lettura, aggiornamento ed eliminazione (CRUD) come parte di una transazione.

avvertimento

Come best practice, cerca di rendere le tue transazioni di scrittura rigorosamente idempotenti.

Rendere le transazioni idempotenti

Ti consigliamo di effettuare transazioni di scrittura idempotenti per evitare effetti collaterali imprevisti in caso di nuovi tentativi. Una transazione è idempotente se può essere eseguita più volte e produrre risultati identici ogni volta.

Ad esempio, si consideri una transazione che inserisce un documento in una tabella denominataPerson. La transazione deve innanzitutto verificare se il documento esiste già o meno nella tabella. Senza questo controllo, la tabella potrebbe contenere documenti duplicati.

Supponiamo che QLDB esegua correttamente la transazione sul lato server, ma che il client scada in attesa di una risposta. Se la transazione non è idempotente, lo stesso documento potrebbe essere inserito più di una volta in caso di nuovo tentativo.

Utilizzo degli indici per evitare la scansione completa delle tabelle

Si consiglia inoltre di eseguire istruzioni con una clausolaWHERE predicativa utilizzando un operatore di uguaglianza su un campo indicizzato o un ID di documento, ad esempioWHERE indexedField = 123 oWHERE indexedField IN (456, 789). Senza questa ricerca indicizzata, QLDB deve eseguire una scansione della tabella, che può portare a timeout delle transazioni o conflitti OCC (Optimistic Concurrency Control).

Per ulteriori informazioni su OCC, consultaModello di concorrenza Amazon QLDB.

Transazioni create implicitamente

Il metodo Amazon.QLDB.driver.iQldbDriver .Execute accetta una funzione lambda che riceve un'istanza di Amazon.QLDB.driver. TransactionExecutor, che è possibile utilizzare per eseguire istruzioni. L'istanza diTransactionExecutor avvolge una transazione creata implicitamente.

È possibile eseguire istruzioni all'interno della funzione lambda utilizzando ilExecute metodo dell'esecutore della transazione. Il driver esegue implicitamente la transazione quando la funzione lambda ritorna.

Le sezioni seguenti mostrano come eseguire operazioni CRUD di base, specificare una logica di ripetizione personalizzata e implementare vincoli di unicità.

Creazione di tabelle

Async
IAsyncResult<Table> createResult = await driver.Execute(async txn => { IQuery<Table> query = txn.Query<Table>("CREATE TABLE Person"); return await txn.Execute(query); }); await foreach (var result in createResult) { Console.WriteLine("{ tableId: " + result.TableId + " }"); // The statement returns the created table ID: // { tableId: 4o5Uk09OcjC6PpJpLahceE } }
Sync
IResult<Table> createResult = driver.Execute( txn => { IQuery<Table> query = txn.Query<Table>("CREATE TABLE Person"); return txn.Execute(query); }); foreach (var result in createResult) { Console.WriteLine("{ tableId: " + result.TableId + " }"); // The statement returns the created table ID: // { tableId: 4o5Uk09OcjC6PpJpLahceE } }
Async
// The result from driver.Execute() is buffered into memory because once the // transaction is committed, streaming the result is no longer possible. IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("CREATE TABLE Person"); }); await foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the created table ID: // { // tableId: "4o5Uk09OcjC6PpJpLahceE" // } }
Sync
// The result from driver.Execute() is buffered into memory because once the // transaction is committed, streaming the result is no longer possible. IResult result = driver.Execute(txn => { return txn.Execute("CREATE TABLE Person"); }); foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the created table ID: // { // tableId: "4o5Uk09OcjC6PpJpLahceE" // } }

Creazione di indici

Async
IAsyncResult<Table> createResult = await driver.Execute(async txn => { IQuery<Table> query = txn.Query<Table>("CREATE INDEX ON Person(firstName)"); return await txn.Execute(query); }); await foreach (var result in createResult) { Console.WriteLine("{ tableId: " + result.TableId + " }"); // The statement returns the updated table ID: // { tableId: 4o5Uk09OcjC6PpJpLahceE } }
Sync
IResult<Table> createResult = driver.Execute(txn => { IQuery<Table> query = txn.Query<Table>("CREATE INDEX ON Person(firstName)"); return txn.Execute(query); }); foreach (var result in createResult) { Console.WriteLine("{ tableId: " + result.TableId + " }"); // The statement returns the updated table ID: // { tableId: 4o5Uk09OcjC6PpJpLahceE } }
Async
IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("CREATE INDEX ON Person(GovId)"); }); await foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the updated table ID: // { // tableId: "4o5Uk09OcjC6PpJpLahceE" // } }
Sync
IResult result = driver.Execute(txn => { return txn.Execute("CREATE INDEX ON Person(GovId)"); }); foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the updated table ID: // { // tableId: "4o5Uk09OcjC6PpJpLahceE" // } }

Lettura di documenti

// Assumes that Person table has documents as follows: // { "GovId": "TOYENC486FH", "FirstName" : "Brent" } // Person class is defined as follows: // public class Person // { // public string GovId { get; set; } // public string FirstName { get; set; } // } IAsyncResult<Person> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = 'TOYENC486FH'")); }); await foreach (Person person in result) { Console.WriteLine(person.GovId); // Prints TOYENC486FH. Console.WriteLine(person.FirstName); // Prints Brent. }
Nota

Quando si esegue una query senza una ricerca indicizzata, viene richiamata una scansione completa della tabella. In questo esempio, consigliamo di avere un indice sulGovId campo per ottimizzare le prestazioni. Senza un indice attivoGovId, le query possono avere una maggiore latenza e possono anche portare a eccezioni di conflitto OCC o a timeout delle transazioni.

Utilizzo dei parametri della query

L'esempio di codice seguente utilizza un parametro di interrogazione di tipo C#.

IAsyncResult<Person> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "Brent")); }); await foreach (Person person in result) { Console.WriteLine(person.GovId); // Prints TOYENC486FH. Console.WriteLine(person.FirstName); // Prints Brent. }

L'esempio di codice seguente utilizza più parametri di interrogazione di tipo C#.

IAsyncResult<Person> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = ? AND FirstName = ?", "TOYENC486FH", "Brent")); }); await foreach (Person person in result) { Console.WriteLine(person.GovId); // Prints TOYENC486FH. Console.WriteLine(person.FirstName); // Prints Brent. }

L'esempio di codice seguente utilizza una matrice di parametri di query di tipo C#.

// Assumes that Person table has documents as follows: // { "GovId": "TOYENC486FH", "FirstName" : "Brent" } // { "GovId": "ROEE1C1AABH", "FirstName" : "Jim" } // { "GovId": "YH844DA7LDB", "FirstName" : "Mary" } string[] ids = { "TOYENC486FH", "ROEE1C1AABH", "YH844DA7LDB" }; IAsyncResult<Person> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId IN (?,?,?)", ids)); }); await foreach (Person person in result) { Console.WriteLine(person.FirstName); // Prints Brent on first iteration. // Prints Jim on second iteration. // Prints Mary on third iteration. }

L'esempio di codice seguente utilizza un elenco C# come valore.

// Assumes that Person table has document as follows: // { "GovId": "TOYENC486FH", // "FirstName" : "Brent", // "Vehicles": [ // { "Make": "Volkswagen", // "Model": "Golf"}, // { "Make": "Honda", // "Model": "Civic"} // ] // } // Person class is defined as follows: // public class Person // { // public string GovId { get; set; } // public string FirstName { get; set; } // public List<Vehicle> Vehicles { get; set; } // } // Vehicle class is defined as follows: // public class Vehicle // { // public string Make { get; set; } // public string Model { get; set; } // } List<Vehicle> vehicles = new List<Vehicle> { new Vehicle { Make = "Volkswagen", Model = "Golf" }, new Vehicle { Make = "Honda", Model = "Civic" } }; IAsyncResult<Person> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE Vehicles = ?", vehicles)); }); await foreach (Person person in result) { Console.WriteLine("{"); Console.WriteLine($" GovId: {person.GovId},"); Console.WriteLine($" FirstName: {person.FirstName},"); Console.WriteLine(" Vehicles: ["); foreach (Vehicle vehicle in person.Vehicles) { Console.WriteLine(" {"); Console.WriteLine($" Make: {vehicle.Make},"); Console.WriteLine($" Model: {vehicle.Model},"); Console.WriteLine(" },"); } Console.WriteLine(" ]"); Console.WriteLine("}"); // Prints: // { // GovId: TOYENC486FH, // FirstName: Brent, // Vehicles: [ // { // Make: Volkswagen, // Model: Golf // }, // { // Make: Honda, // Model: Civic // }, // ] // } }
Async
// Assumes that Person table has documents as follows: // { "GovId": "TOYENC486FH", "FirstName" : "Brent" } IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE GovId = 'TOYENC486FH'"); }); await foreach (IIonValue row in result) { Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH. Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent. }
Sync
// Assumes that Person table has documents as follows: // { "GovId": "TOYENC486FH", "FirstName" : "Brent" } IResult result = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE GovId = 'TOYENC486FH'"); }); foreach (IIonValue row in result) { Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH. Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent. }
Nota

Quando si esegue una query senza una ricerca indicizzata, viene richiamata una scansione completa della tabella. In questo esempio, consigliamo di avere un indice sulGovId campo per ottimizzare le prestazioni. Senza un indice attivoGovId, le query possono avere una maggiore latenza e possono anche portare a eccezioni di conflitto OCC o a timeout delle transazioni.

L'esempio di codice seguente utilizza un parametro di interrogazione di tipo Ion.

Async
IValueFactory valueFactory = new ValueFactory(); IIonValue ionFirstName = valueFactory.NewString("Brent"); IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE FirstName = ?", ionFirstName); }); await foreach (IIonValue row in result) { Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH. Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent. }
Sync
IValueFactory valueFactory = new ValueFactory(); IIonValue ionFirstName = valueFactory.NewString("Brent"); IResult result = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE FirstName = ?", ionFirstName); }); foreach (IIonValue row in result) { Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH. Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent. }

Il seguente esempio di codice utilizza più parametri di interrogazione.

Async
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionFirstName = valueFactory.NewString("Brent"); IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE GovId = ? AND FirstName = ?", ionGovId, ionFirstName); }); await foreach (IIonValue row in result) { Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH. Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent. }
Sync
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionFirstName = valueFactory.NewString("Brent"); IResult result = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE GovId = ? AND FirstName = ?", ionGovId, ionFirstName); }); foreach (IIonValue row in result) { Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH. Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent. }

L'esempio di codice seguente utilizza un elenco di parametri di interrogazione.

Async
// Assumes that Person table has documents as follows: // { "GovId": "TOYENC486FH", "FirstName" : "Brent" } // { "GovId": "ROEE1C1AABH", "FirstName" : "Jim" } // { "GovId": "YH844DA7LDB", "FirstName" : "Mary" } IIonValue[] ionIds = { valueFactory.NewString("TOYENC486FH"), valueFactory.NewString("ROEE1C1AABH"), valueFactory.NewString("YH844DA7LDB") }; IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE GovId IN (?,?,?)", ionIds); }); await foreach (IIonValue row in result) { Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent on first iteration. // Prints Jim on second iteration. // Prints Mary on third iteration. }
Sync
// Assumes that Person table has documents as follows: // { "GovId": "TOYENC486FH", "FirstName" : "Brent" } // { "GovId": "ROEE1C1AABH", "FirstName" : "Jim" } // { "GovId": "YH844DA7LDB", "FirstName" : "Mary" } IIonValue[] ionIds = { valueFactory.NewString("TOYENC486FH"), valueFactory.NewString("ROEE1C1AABH"), valueFactory.NewString("YH844DA7LDB") }; IResult result = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE GovId IN (?,?,?)", ionIds); }); foreach (IIonValue row in result) { Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent on first iteration. // Prints Jim on second iteration. // Prints Mary on third iteration. }

L'esempio di codice seguente utilizza un elenco Ion come valore. Per ulteriori informazioni sull'utilizzo dei diversi tipi di Ion, consultaUtilizzo dei tipi di dati Amazon Ion in Amazon QLDB.

Async
// Assumes that Person table has document as follows: // { "GovId": "TOYENC486FH", // "FirstName" : "Brent", // "Vehicles": [ // { "Make": "Volkswagen", // "Model": "Golf"}, // { "Make": "Honda", // "Model": "Civic"} // ] // } IIonValue ionVehicle1 = valueFactory.NewEmptyStruct(); ionVehicle1.SetField("Make", valueFactory.NewString("Volkswagen")); ionVehicle1.SetField("Model", valueFactory.NewString("Golf")); IIonValue ionVehicle2 = valueFactory.NewEmptyStruct(); ionVehicle2.SetField("Make", valueFactory.NewString("Honda")); ionVehicle2.SetField("Model", valueFactory.NewString("Civic")); IIonValue ionVehicles = valueFactory.NewEmptyList(); ionVehicles.Add(ionVehicle1); ionVehicles.Add(ionVehicle2); IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE Vehicles = ?", ionVehicles); }); await foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // Prints: // { // GovId: "TOYENC486FN", // FirstName: "Brent", // Vehicles: [ // { // Make: "Volkswagen", // Model: "Golf" // }, // { // Make: "Honda", // Model: "Civic" // } // ] // } }
Sync
// Assumes that Person table has document as follows: // { "GovId": "TOYENC486FH", // "FirstName" : "Brent", // "Vehicles": [ // { "Make": "Volkswagen", // "Model": "Golf"}, // { "Make": "Honda", // "Model": "Civic"} // ] // } IIonValue ionVehicle1 = valueFactory.NewEmptyStruct(); ionVehicle1.SetField("Make", valueFactory.NewString("Volkswagen")); ionVehicle1.SetField("Model", valueFactory.NewString("Golf")); IIonValue ionVehicle2 = valueFactory.NewEmptyStruct(); ionVehicle2.SetField("Make", valueFactory.NewString("Honda")); ionVehicle2.SetField("Model", valueFactory.NewString("Civic")); IIonValue ionVehicles = valueFactory.NewEmptyList(); ionVehicles.Add(ionVehicle1); ionVehicles.Add(ionVehicle2); IResult result = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE Vehicles = ?", ionVehicles); }); foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // Prints: // { // GovId: "TOYENC486FN", // FirstName: "Brent", // Vehicles: [ // { // Make: "Volkswagen", // Model: "Golf" // }, // { // Make: "Honda", // Model: "Civic" // } // ] // } }

Inserimento dei documenti

Il seguente esempio di codice inserisce i tipi di dati Ion.

string govId = "TOYENC486FH"; Person person = new Person { GovId = "TOYENC486FH", FirstName = "Brent" }; await driver.Execute(async txn => { // Check if a document with GovId:TOYENC486FH exists // This is critical to make this transaction idempotent IAsyncResult<Person> result = await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = ?", govId)); // Check if there is a record in the cursor. int count = await result.CountAsync(); if (count > 0) { // Document already exists, no need to insert return; } // Insert the document. await txn.Execute(txn.Query<Document>("INSERT INTO Person ?", person)); });
Async
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH")); ionPerson.SetField("FirstName", valueFactory.NewString("Brent")); await driver.Execute(async txn => { // Check if a document with GovId:TOYENC486FH exists // This is critical to make this transaction idempotent IAsyncResult result = await txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId); // Check if there is a record in the cursor. int count = await result.CountAsync(); if (count > 0) { // Document already exists, no need to insert return; } // Insert the document. await txn.Execute("INSERT INTO Person ?", ionPerson); });
Sync
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH")); ionPerson.SetField("FirstName", valueFactory.NewString("Brent")); driver.Execute(txn => { // Check if a document with GovId:TOYENC486FH exists // This is critical to make this transaction idempotent IResult result = txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId); // Check if there is a record in the cursor. int count = result.Count(); if (count > 0) { // Document already exists, no need to insert return; } // Insert the document. txn.Execute("INSERT INTO Person ?", ionPerson); });

Questa transazione inserisce un documento nellaPerson tabella. Prima dell'inserimento, controlla innanzitutto se il documento esiste già nella tabella. Questo controllo rende la transazione di natura idempotente. Anche se esegui questa transazione più volte, non causerà effetti collaterali indesiderati.

Nota

In questo esempio, consigliamo di avere un indice sulGovId campo per ottimizzare le prestazioni. Senza un indice attivoGovId, le dichiarazioni possono avere una maggiore latenza e possono anche portare a eccezioni di conflitto OCC o a timeout delle transazioni.

Inserimento di più documenti in un'unica dichiarazione

Per inserire più documenti utilizzando una singolaINSERT istruzione, è possibile passare unList parametro C# all'istruzione come segue.

Person person1 = new Person { FirstName = "Brent", GovId = "TOYENC486FH" }; Person person2 = new Person { FirstName = "Jim", GovId = "ROEE1C1AABH" }; List<Person> people = new List<Person>(); people.Add(person1); people.Add(person2); IAsyncResult<Document> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Document>("INSERT INTO Person ?", people)); }); await foreach (Document row in result) { Console.WriteLine("{ documentId: " + row.DocumentId + " }"); // The statement returns the created documents' ID: // { documentId: 6BFt5eJQDFLBW2aR8LPw42 } // { documentId: K5Zrcb6N3gmIEHgGhwoyKF } }

Per inserire più documenti utilizzando una singolaINSERT istruzione, è possibile passare un parametro di tipo Ion list all'istruzione come segue.

Async
IIonValue ionPerson1 = valueFactory.NewEmptyStruct(); ionPerson1.SetField("FirstName", valueFactory.NewString("Brent")); ionPerson1.SetField("GovId", valueFactory.NewString("TOYENC486FH")); IIonValue ionPerson2 = valueFactory.NewEmptyStruct(); ionPerson2.SetField("FirstName", valueFactory.NewString("Jim")); ionPerson2.SetField("GovId", valueFactory.NewString("ROEE1C1AABH")); IIonValue ionPeople = valueFactory.NewEmptyList(); ionPeople.Add(ionPerson1); ionPeople.Add(ionPerson2); IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("INSERT INTO Person ?", ionPeople); }); await foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the created documents' ID: // { // documentId: "6BFt5eJQDFLBW2aR8LPw42" // } // // { // documentId: "K5Zrcb6N3gmIEHgGhwoyKF" // } }
Sync
IIonValue ionPerson1 = valueFactory.NewEmptyStruct(); ionPerson1.SetField("FirstName", valueFactory.NewString("Brent")); ionPerson1.SetField("GovId", valueFactory.NewString("TOYENC486FH")); IIonValue ionPerson2 = valueFactory.NewEmptyStruct(); ionPerson2.SetField("FirstName", valueFactory.NewString("Jim")); ionPerson2.SetField("GovId", valueFactory.NewString("ROEE1C1AABH")); IIonValue ionPeople = valueFactory.NewEmptyList(); ionPeople.Add(ionPerson1); ionPeople.Add(ionPerson2); IResult result = driver.Execute(txn => { return txn.Execute("INSERT INTO Person ?", ionPeople); }); foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the created documents' ID: // { // documentId: "6BFt5eJQDFLBW2aR8LPw42" // } // // { // documentId: "K5Zrcb6N3gmIEHgGhwoyKF" // } }

Non si racchiude il segnaposto variabile (?) tra parentesi a doppio angolo (<<...>>) quando si passa un elenco di Ion. Nelle istruzioni PartiQL, le parentesi a doppio angolo indicano una raccolta non ordinata nota come borsa.

Aggiornamento dei documenti

string govId = "TOYENC486FH"; string firstName = "John"; IAsyncResult<Document> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Document>("UPDATE Person SET FirstName = ? WHERE GovId = ?", firstName , govId)); }); await foreach (Document row in result) { Console.WriteLine("{ documentId: " + row.DocumentId + " }"); // The statement returns the updated document ID: // { documentId: Djg30Zoltqy5M4BFsA2jSJ } }
Async
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionFirstName = valueFactory.NewString("John"); IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("UPDATE Person SET FirstName = ? WHERE GovId = ?", ionFirstName , ionGovId); }); await foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the updated document ID: // { // documentId: "Djg30Zoltqy5M4BFsA2jSJ" // } }
Sync
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionFirstName = valueFactory.NewString("John"); IResult result = driver.Execute(txn => { return txn.Execute("UPDATE Person SET FirstName = ? WHERE GovId = ?", ionFirstName , ionGovId); }); foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the updated document ID: // { // documentId: "Djg30Zoltqy5M4BFsA2jSJ" // } }
Nota

In questo esempio, consigliamo di avere un indice sulGovId campo per ottimizzare le prestazioni. Senza un indice attivoGovId, le dichiarazioni possono avere una maggiore latenza e possono anche portare a eccezioni di conflitto OCC o a timeout delle transazioni.

Eliminazione di documenti

string govId = "TOYENC486FH"; IAsyncResult<Document> result = await driver.Execute(async txn => { return await txn.Execute(txn.Query<Document>("DELETE FROM Person WHERE GovId = ?", govId)); }); await foreach (Document row in result) { Console.WriteLine("{ documentId: " + row.DocumentId + " }"); // The statement returns the updated document ID: // { documentId: Djg30Zoltqy5M4BFsA2jSJ } }
Async
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IAsyncResult result = await driver.Execute(async txn => { return await txn.Execute("DELETE FROM Person WHERE GovId = ?", ionGovId); }); await foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the deleted document ID: // { // documentId: "Djg30Zoltqy5M4BFsA2jSJ" // } }
Sync
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IResult result = driver.Execute(txn => { return txn.Execute("DELETE FROM Person WHERE GovId = ?", ionGovId); }); foreach (IIonValue row in result) { Console.WriteLine(row.ToPrettyString()); // The statement returns the deleted document ID: // { // documentId: "Djg30Zoltqy5M4BFsA2jSJ" // } }
Nota

In questo esempio, consigliamo di avere un indice sulGovId campo per ottimizzare le prestazioni. Senza un indice attivoGovId, le dichiarazioni possono avere una maggiore latenza e possono anche portare a eccezioni di conflitto OCC o a timeout delle transazioni.

Esecuzione di più rendiconti in una transazione

// This code snippet is intentionally trivial. In reality you wouldn't do this because you'd // set your UPDATE to filter on vin and insured, and check if you updated something or not. public static async Task<bool> InsureVehicle(IAsyncQldbDriver driver, string vin) { return await driver.Execute(async txn => { // Check if the vehicle is insured. Amazon.QLDB.Driver.Generic.IAsyncResult<Vehicle> result = await txn.Execute( txn.Query<Vehicle>("SELECT insured FROM Vehicles WHERE vin = ? AND insured = FALSE", vin)); if (await result.CountAsync() > 0) { // If the vehicle is not insured, insure it. await txn.Execute( txn.Query<Document>("UPDATE Vehicles SET insured = TRUE WHERE vin = ?", vin)); return true; } return false; }); }
Async
// This code snippet is intentionally trivial. In reality you wouldn't do this because you'd // set your UPDATE to filter on vin and insured, and check if you updated something or not. public static async Task<bool> InsureVehicle(IAsyncQldbDriver driver, string vin) { ValueFactory valueFactory = new ValueFactory(); IIonValue ionVin = valueFactory.NewString(vin); return await driver.Execute(async txn => { // Check if the vehicle is insured. Amazon.QLDB.Driver.IAsyncResult result = await txn.Execute( "SELECT insured FROM Vehicles WHERE vin = ? AND insured = FALSE", ionVin); if (await result.CountAsync() > 0) { // If the vehicle is not insured, insure it. await txn.Execute( "UPDATE Vehicles SET insured = TRUE WHERE vin = ?", ionVin); return true; } return false; }); }

Logica di ripetizione dei tentativi

Per informazioni sulla logica di ripetizione integrata nel driver, vedereInformazioni sulla politica di riprova con il driver in Amazon QLDB.

Implementazione dei vincoli di unicità

QLDB non supporta indici univoci, ma puoi implementare questo comportamento nella tua applicazione.

Si supponga di voler implementare un vincolo di unicità sulGovId campo dellaPerson tabella. Questa operazione può essere eseguita in modo da scrivere una transazione che esegue le seguenti operazioni:

  1. Asserisci che la tabella non ha documenti esistenti con un valore specificatoGovId.

  2. Inserisci il documento se l'asserzione è valida.

Se una transazione concorrente supera contemporaneamente l'asserzione, solo una delle transazioni verrà confermata con successo. L'altra transazione avrà esito negativo con un'eccezione di conflitto OCC.

L'esempio di codice seguente mostra come implementare questa logica di vincolo di unicità.

string govId = "TOYENC486FH"; Person person = new Person { GovId = "TOYENC486FH", FirstName = "Brent" }; await driver.Execute(async txn => { // Check if a document with GovId:TOYENC486FH exists // This is critical to make this transaction idempotent IAsyncResult<Person> result = await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = ?", govId)); // Check if there is a record in the cursor. int count = await result.CountAsync(); if (count > 0) { // Document already exists, no need to insert return; } // Insert the document. await txn.Execute(txn.Query<Document>("INSERT INTO Person ?", person)); });
Async
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH")); ionPerson.SetField("FirstName", valueFactory.NewString("Brent")); await driver.Execute(async txn => { // Check if a document with GovId:TOYENC486FH exists // This is critical to make this transaction idempotent IAsyncResult result = await txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId); // Check if there is a record in the cursor. int count = await result.CountAsync(); if (count > 0) { // Document already exists, no need to insert return; } // Insert the document. await txn.Execute("INSERT INTO Person ?", ionPerson); });
Sync
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH"); IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH")); ionPerson.SetField("FirstName", valueFactory.NewString("Brent")); driver.Execute(txn => { // Check if a document with GovId:TOYENC486FH exists // This is critical to make this transaction idempotent IResult result = txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId); // Check if there is a record in the cursor. int count = result.Count(); if (count > 0) { // Document already exists, no need to insert return; } // Insert the document. txn.Execute("INSERT INTO Person ?", ionPerson); });
Nota

In questo esempio, consigliamo di avere un indice sulGovId campo per ottimizzare le prestazioni. Senza un indice attivoGovId, le dichiarazioni possono avere una maggiore latenza e possono anche portare a eccezioni di conflitto OCC o a timeout delle transazioni.

Uso di Amazon Ion

Esistono diversi modi per elaborare i dati Amazon Ion in QLDB. È possibile utilizzare la libreria Ion per creare e modificare i valori Ion. In alternativa, è possibile utilizzare il mappatore di oggetti Ion per mappare vecchi oggetti CLR (POCO) semplici in C# da e verso i valori Ion. La versione 1.3.0 del driver QLDB per .NET introduce il supporto per il mappatore di oggetti Ion.

Le sezioni seguenti forniscono esempi di codice di elaborazione dei dati Ion utilizzando entrambe le tecniche.

Importazione del modulo Ion

using Amazon.IonObjectMapper;
using Amazon.IonDotnet.Builders;

Creazione di tipi di ioni

L'esempio di codice seguente mostra come eseguire operazioni di creazione di oggetti C# utilizzando la mappatrice di oggetti Ion.

// Assumes that Person class is defined as follows: // public class Person // { // public string FirstName { get; set; } // public int Age { get; set; } // } // Initialize the Ion Object Mapper IonSerializer ionSerializer = new IonSerializer(); // The C# object to be serialized Person person = new Person { FirstName = "John", Age = 13 }; // Serialize the C# object into stream using the Ion Object Mapper Stream stream = ionSerializer.Serialize(person); // Load will take in stream and return a datagram; a top level container of Ion values. IIonValue ionDatagram = IonLoader.Default.Load(stream); // To get the Ion value within the datagram, we call GetElementAt(0). IIonValue ionPerson = ionDatagram.GetElementAt(0); Console.WriteLine(ionPerson.GetField("firstName").StringValue); Console.WriteLine(ionPerson.GetField("age").IntValue);

I seguenti esempi di codice mostrano i due modi per creare valori Ion utilizzando la libreria Ion.

Uso di ValueFactory

using Amazon.IonDotnet.Tree; using Amazon.IonDotnet.Tree.Impl; IValueFactory valueFactory = new ValueFactory(); IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("firstName", valueFactory.NewString("John")); ionPerson.SetField("age", valueFactory.NewInt(13)); Console.WriteLine(ionPerson.GetField("firstName").StringValue); Console.WriteLine(ionPerson.GetField("age").IntValue);

Uso di IonLoader

using Amazon.IonDotnet.Builders; using Amazon.IonDotnet.Tree; // Load will take in Ion text and return a datagram; a top level container of Ion values. IIonValue ionDatagram = IonLoader.Default.Load("{firstName: \"John\", age: 13}"); // To get the Ion value within the datagram, we call GetElementAt(0). IIonValue ionPerson = ionDatagram.GetElementAt(0); Console.WriteLine(ionPerson.GetField("firstName").StringValue); Console.WriteLine(ionPerson.GetField("age").IntValue);

Ottenere un dump binario Ion

// Initialize the Ion Object Mapper with Ion binary serialization format IonSerializer ionSerializer = new IonSerializer(new IonSerializationOptions { Format = IonSerializationFormat.BINARY }); // The C# object to be serialized Person person = new Person { FirstName = "John", Age = 13 }; MemoryStream stream = (MemoryStream) ionSerializer.Serialize(person); Console.WriteLine(BitConverter.ToString(stream.ToArray()));
// ionObject is an Ion struct MemoryStream stream = new MemoryStream(); using (var writer = IonBinaryWriterBuilder.Build(stream)) { ionObject.WriteTo(writer); writer.Finish(); } Console.WriteLine(BitConverter.ToString(stream.ToArray()));

Ottenere un dump di testo Ion

// Initialize the Ion Object Mapper IonSerializer ionSerializer = new IonSerializer(new IonSerializationOptions { Format = IonSerializationFormat.TEXT }); // The C# object to be serialized Person person = new Person { FirstName = "John", Age = 13 }; MemoryStream stream = (MemoryStream) ionSerializer.Serialize(person); Console.WriteLine(System.Text.Encoding.UTF8.GetString(stream.ToArray()));
// ionObject is an Ion struct StringWriter sw = new StringWriter(); using (var writer = IonTextWriterBuilder.Build(sw)) { ionObject.WriteTo(writer); writer.Finish(); } Console.WriteLine(sw.ToString());

Per ulteriori informazioni sull'utilizzo di Ion, consulta la documentazione di Amazon Ion su GitHub. Per altri esempi di codice sull'utilizzo di Ion in QLDB, vedereUtilizzo dei tipi di dati Amazon Ion in Amazon QLDB.