Amazon QLDB driver for Python – Quick start tutorial - Amazon Quantum Ledger Database (Amazon QLDB)

Amazon QLDB driver for Python – Quick start tutorial

In this tutorial, you learn how to set up a simple application using the latest version of the Amazon QLDB driver for Python. This guide includes steps for installing the driver and short code examples of basic create, read, update, and delete (CRUD) operations. For more in-depth examples that demonstrate these operations in a full sample application, see the Python tutorial.

Prerequisites

Before you get started, make sure that you do the following:

  1. Complete the Prerequisites for the Python driver, if you haven't already done so. This includes signing up for AWS, getting an AWS access key for development, and installing Python version 3.6 or later.

  2. Create a ledger named quick-start.

    To learn how to create a ledger, see Basic operations for Amazon QLDB ledgers or Step 1: Create a new ledger in Getting started with the console.

Step 1: Set up your project

First, set up your Python project.

Note

If you use an IDE that has features to automate these setup steps, you can skip ahead to Step 2: Initialize the driver.

  1. Create a folder for your application.

    $ mkdir myproject $ cd myproject
  2. To install the QLDB driver for Python from PyPI, enter the following pip command.

    $ pip install pyqldb

    Installing the driver also installs its dependencies, including the AWS SDK for Python (Boto3) and Amazon Ion packages.

  3. Create a new file named app.py.

    Then, incrementally add the code examples in the following steps to try some basic CRUD operations. Or, you can skip the step-by-step tutorial and instead run the complete application.

Step 2: Initialize the driver

Initialize an instance of the driver that connects to the ledger named quick-start. Add the following code to your app.py file.

from pyqldb.config.retry_config import RetryConfig from pyqldb.driver.qldb_driver import QldbDriver # Configure retry limit to 3 retry_config = RetryConfig(retry_limit=3) # Initialize the driver print("Initializing the driver") qldb_driver = QldbDriver("quick-start", retry_config=retry_config)

Step 3: Create a table and an index

The following code example shows how to run CREATE TABLE and CREATE INDEX statements.

Add the following code that creates a table named People and an index for the lastName field on that table. Indexes are required to optimize query performance and help to limit optimistic concurrency control (OCC) conflict exceptions.

def create_table(transaction_executor): print("Creating a table") transaction_executor.execute_statement("Create TABLE People") def create_index(transaction_executor): print("Creating an index") transaction_executor.execute_statement("CREATE INDEX ON People(lastName)") # Create a table qldb_driver.execute_lambda(lambda executor: create_table(executor)) # Create an index on the table qldb_driver.execute_lambda(lambda executor: create_index(executor))

Step 4: Insert a document

The following code example shows how to run an INSERT statement. QLDB supports the PartiQL query language (SQL compatible) and the Amazon Ion data format (superset of JSON).

Add the following code that inserts a document into the People table.

def insert_documents(transaction_executor, arg_1): print("Inserting a document") transaction_executor.execute_statement("INSERT INTO People ?", arg_1) # Insert a document doc_1 = { 'firstName': "John", 'lastName': "Doe", 'age': 32, } qldb_driver.execute_lambda(lambda x: insert_documents(x, doc_1))

This example uses a question mark (?) as a variable placeholder to pass the document information to the statement. The execute_statement method supports values in both Amazon Ion types and Python native types.

Tip

To insert multiple documents by using a single INSERT statement, you can pass a parameter of type list to the statement as follows.

# people is a list transaction_executor.execute_statement("INSERT INTO Person ?", people)

You don't enclose the variable placeholder (?) in double angle brackets ( <<...>> ) when passing a list. In manual PartiQL statements, double angle brackets denote an unordered collection known as a bag.

Step 5: Query the document

The following code example shows how to run a SELECT statement.

Add the following code that queries a document from the People table.

def read_documents(transaction_executor): print("Querying the table") cursor = transaction_executor.execute_statement("SELECT * FROM People WHERE lastName = ?", 'Doe') for doc in cursor: print(doc["firstName"]) print(doc["lastName"]) print(doc["age"]) # Query the table qldb_driver.execute_lambda(lambda executor: read_documents(executor))

Step 6: Update the document

The following code example shows how to run an UPDATE statement.

  1. Add the following code that updates a document in the People table by updating age to 42.

    def update_documents(transaction_executor, age, lastName): print("Updating the document") transaction_executor.execute_statement("UPDATE People SET age = ? WHERE lastName = ?", age, lastName) # Update the document age = 42 lastName = 'Doe' qldb_driver.execute_lambda(lambda x: update_documents(x, age, lastName))
  2. Query the table again to see the updated value.

    # Query the updated document qldb_driver.execute_lambda(lambda executor: read_documents(executor))
  3. To run the application, enter the following command from your project directory.

    $ python app.py

Running the complete application

The following code example is the complete version of the app.py application. Instead of doing the previous steps individually, you can also copy and run this code example end to end. This application demonstrates some basic CRUD operations on the ledger named quick-start.

Note

Before you run this code, make sure that you don't already have an active table named People in the quick-start ledger.

from pyqldb.config.retry_config import RetryConfig from pyqldb.driver.qldb_driver import QldbDriver def create_table(transaction_executor): print("Creating a table") transaction_executor.execute_statement("CREATE TABLE People") def create_index(transaction_executor): print("Creating an index") transaction_executor.execute_statement("CREATE INDEX ON People(lastName)") def insert_documents(transaction_executor, arg_1): print("Inserting a document") transaction_executor.execute_statement("INSERT INTO People ?", arg_1) def read_documents(transaction_executor): print("Querying the table") cursor = transaction_executor.execute_statement("SELECT * FROM People WHERE lastName = ?", 'Doe') for doc in cursor: print(doc["firstName"]) print(doc["lastName"]) print(doc["age"]) def update_documents(transaction_executor, age, lastName): print("Updating the document") transaction_executor.execute_statement("UPDATE People SET age = ? WHERE lastName = ?", age, lastName) # Configure retry limit to 3 retry_config = RetryConfig(retry_limit=3) # Initialize the driver print("Initializing the driver") qldb_driver = QldbDriver("quick-start", retry_config=retry_config) # Create a table qldb_driver.execute_lambda(lambda executor: create_table(executor)) # Create an index on the table qldb_driver.execute_lambda(lambda executor: create_index(executor)) # Insert a document doc_1 = { 'firstName': "John", 'lastName': "Doe", 'age': 32, } qldb_driver.execute_lambda(lambda x: insert_documents(x, doc_1)) # Query the table qldb_driver.execute_lambda(lambda executor: read_documents(executor)) # Update the document age = 42 lastName = 'Doe' qldb_driver.execute_lambda(lambda x: update_documents(x, age, lastName)) # Query the table for the updated document qldb_driver.execute_lambda(lambda executor: read_documents(executor))

To run the complete application, enter the following command from your project directory.

$ python app.py