Getting Started with Cloud Spanner in Python

Getting Started with Cloud Spanner in Python

Objectives

This tutorial walks you through the following steps using the Cloud Spanner client library for Python:

  • Create a Cloud Spanner instance and database.
  • Write, read, and execute SQL queries on data in the database.
  • Update the database schema.
  • Update data using a read-write transaction.
  • Add a secondary index to the database.
  • Use the index to read and execute SQL queries on data.
  • Retrieve data using a read-only transaction.

Costs

This tutorial uses Cloud Spanner, which is a billable component of the Google Cloud Platform. For information on the cost of using Cloud Spanner, see Pricing.

Before you begin

  1. Complete the steps described in Set Up, which covers creating and setting a default Google Cloud Platform project, enabling billing, enabling the Cloud Spanner API, and setting up OAuth 2.0 to get authentication credentials to use the Cloud Spanner API.

    In particular, ensure that you run gcloud auth application-default login to set up your local development environment with authentication credentials.

  2. Follow the instructions in Setting Up a Python Development Environment.

  3. Clone the sample app repository to your local machine:

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
    

    Alternatively, you can download the sample as a zip file and extract it.

  4. Change to the directory that contains the Cloud Spanner sample code:

    cd python-docs-samples/spanner/cloud-client
    
  5. Create an isolated Python environment, and install dependencies:

    virtualenv env
    source env/bin/activate
    pip install -r requirements.txt
    

Create an instance

When you first use Cloud Spanner, you must create an instance, which is an allocation of resources that are used by Cloud Spanner databases. When you create an instance, you choose where your data is stored and how many nodes are used for your data. (For more information, see Instances).

Create a Cloud Spanner instance and assign it the instance ID test-instance and the display name Test Instance using the regional configuration regional-us-central1 with a node count of 1 (node_count corresponds to the amount of serving resources available to databases in the instance):

gcloud spanner instances create test-instance --config=regional-us-central1 \
--description="Test Instance" --nodes=1

You should see:

Creating instance...done.

Look through sample files

The samples repo contains a sample that shows how to use Cloud Spanner with Python.

Take a look through the snippets.py file that shows how to use Cloud Spanner. The code shows how to create and use a new database. The data uses the example schema shown in the Schema and Data Model page.

Create a database

Create a database called example-db by running the following at the command line.

python snippets.py test-instance --database-id example-db create_database

You should see:

Created database example-db on instance test-instance

You have just created a Cloud Spanner database. The following is the code that created the database.

def create_database(instance_id, database_id):
    """Creates a database and tables for sample data."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)

    database = instance.database(database_id, ddl_statements=[
        """CREATE TABLE Singers (
            SingerId     INT64 NOT NULL,
            FirstName    STRING(1024),
            LastName     STRING(1024),
            SingerInfo   BYTES(MAX)
        ) PRIMARY KEY (SingerId)""",
        """CREATE TABLE Albums (
            SingerId     INT64 NOT NULL,
            AlbumId      INT64 NOT NULL,
            AlbumTitle   STRING(MAX)
        ) PRIMARY KEY (SingerId, AlbumId),
        INTERLEAVE IN PARENT Singers ON DELETE CASCADE"""
    ])

    operation = database.create()

    print('Waiting for operation to complete...')
    operation.result()

    print('Created database {} on instance {}'.format(
        database_id, instance_id))

The code also defines two tables, Singers and Albums, for a basic music application. These tables are used throughout this page. Take a look at the example schema if you haven't already.

The next step is to write data to your database.

Create a database client

Before you can do reads or writes, you must create a Client. You can think of a Client as a database connection: all of your interactions with Cloud Spanner must go through a Client. Typically you create a Client when your application starts up, then you re-use that Client to read, write, and execute transactions. The following code shows how to create a client.

# Imports the Google Cloud Client Library.
from google.cloud import spanner

# Instantiate a client.
spanner_client = spanner.Client()

# Your Cloud Spanner instance ID.
instance_id = 'my-instance-id'

# Get a Cloud Spanner instance by ID.
instance = spanner_client.instance(instance_id)

# Your Cloud Spanner database ID.
database_id = 'my-database-id'

# Get a Cloud Spanner database by ID.
database = instance.database(database_id)

# Execute a simple SQL statement.
results = database.execute_sql('SELECT 1')

for row in results:
    print(row)

Read more in the Client reference.

Write data

You write data using a Batch object. A Batch object is a container for mutation operations. A mutation represents a sequence of inserts, updates, deletes, etc., that can be applied atomically to different rows and/or tables in a Cloud Spanner database.

The insert() method in the Batch class is used to add one or more insert mutations to the batch. All mutations in a single batch are applied atomically.

This code shows how to write the data:

def insert_data(instance_id, database_id):
    """Inserts sample data into the given database.

    The database and table must already exist and can be created using
    `create_database`.
    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    with database.batch() as batch:
        batch.insert(
            table='Singers',
            columns=('SingerId', 'FirstName', 'LastName',),
            values=[
                (1, u'Marc', u'Richards'),
                (2, u'Catalina', u'Smith'),
                (3, u'Alice', u'Trentor'),
                (4, u'Lea', u'Martin'),
                (5, u'David', u'Lomond')])

        batch.insert(
            table='Albums',
            columns=('SingerId', 'AlbumId', 'AlbumTitle',),
            values=[
                (1, 1, u'Total Junk'),
                (1, 2, u'Go, Go, Go'),
                (2, 1, u'Green'),
                (2, 2, u'Forever Hold Your Peace'),
                (2, 3, u'Terrified')])

    print('Inserted data.')

(For details about the data, see the example schema for the Singers and Albums tables.)

Run the sample using the insert_data argument.

python snippets.py test-instance --database-id example-db insert_data

You should see:

Inserted data.

Query data using SQL

Cloud Spanner supports a native SQL interface for reading data, which you can access on the command line using the gcloud command-line tool or programmatically using the Cloud Spanner client library for Python.

On the command line

Execute the following SQL statement to read the values of all columns from the Albums table:

gcloud spanner databases execute-sql example-db --instance=test-instance --sql='SELECT SingerId, AlbumId, AlbumTitle FROM Albums'

The result should be:

SingerId AlbumId AlbumTitle
1        1       Total Junk
1        2       Go, Go, Go
2        1       Green
2        2       Forever Hold Your Peace
2        3       Terrified

Using the Cloud Spanner client library for Python

In addition to executing a SQL statement on the command line, you can issue the same SQL statement programmatically using the Cloud Spanner client library for Python.

Use the execute_sql() method of the Database class to run the SQL query.

Here's how to issue the query and access the data:

def query_data(instance_id, database_id):
    """Queries sample data from the database using SQL."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    results = database.execute_sql(
        'SELECT SingerId, AlbumId, AlbumTitle FROM Albums')

    for row in results:
        print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row))

Run the sample using the query_data argument.

python snippets.py test-instance --database-id example-db query_data

You should see the following result:

SingerId: 2, AlbumId: 2, AlbumTitle: Forever Hold Your Peace
SingerId: 1, AlbumId: 2, AlbumTitle: Go, Go, Go
SingerId: 2, AlbumId: 1, AlbumTitle: Green
SingerId: 2, AlbumId: 3, AlbumTitle: Terrified
SingerId: 1, AlbumId: 1, AlbumTitle: Total Junk

Read data using the read API

In addition to Cloud Spanner's SQL interface, Cloud Spanner also supports a read interface.

Use the read() method of the Database class to read rows from the database. Use a KeySet object to define a collection of keys and/or key ranges to read.

Here's how to read the data:

def read_data(instance_id, database_id):
    """Reads sample data from the database."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    keyset = spanner.KeySet(all_=True)
    results = database.read(
        table='Albums',
        columns=('SingerId', 'AlbumId', 'AlbumTitle',),
        keyset=keyset,)

    for row in results:
        print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row))

Run the sample using the read_data argument.

python snippets.py test-instance --database-id example-db read_data

You should see output similar to:

SingerId: 1, AlbumId: 1, AlbumTitle: Total Junk
SingerId: 1, AlbumId: 2, AlbumTitle: Go, Go, Go
SingerId: 2, AlbumId: 1, AlbumTitle: Green
SingerId: 2, AlbumId: 2, AlbumTitle: Forever Hold Your Peace
SingerId: 2, AlbumId: 3, AlbumTitle: Terrified

Update the database schema

Assume you need to add a new column called MarketingBudget to the Albums table. Adding a new column to an existing table requires an update to your database schema. Cloud Spanner supports schema updates to a database while the database continues to serve traffic. Schema updates do not require taking the database offline and they do not lock entire tables or columns; you can continue writing data to the database during the schema update. Read more about supported schema updates and schema change performance in Updating schemas.

Add a column

You can add a column on the command line using the gcloud command-line tool or programmatically using the Cloud Spanner client library for Python.

On the command line

Use the following ALTER TABLE command to add the new column to the table:

gcloud spanner databases ddl update example-db --instance=test-instance \
--ddl='ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'

You should see:

DDL updating...done.

Using the Cloud Spanner client library for Python

Use the update_ddl() method of the Database class to modify the schema:

def add_column(instance_id, database_id):
    """Adds a new column to the Albums table in the example database."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    operation = database.update_ddl([
        'ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'])

    print('Waiting for operation to complete...')
    operation.result()

    print('Added the MarketingBudget column.')

Run the sample using the add_column argument.

python snippets.py test-instance --database-id example-db add_column

You should see:

Added the MarketingBudget column.

Write data to the new column

The following code writes data to the new column. It sets MarketingBudget to 100000 for the row keyed by Albums(1, 1) and to 500000 for the row keyed by Albums(2, 2).

def update_data(instance_id, database_id):
    """Updates sample data in the database.

    This updates the `MarketingBudget` column which must be created before
    running this sample. You can add the column by running the `add_column`
    sample or by running this DDL statement against your database:

        ALTER TABLE Albums ADD COLUMN MarketingBudget INT64

    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    with database.batch() as batch:
        batch.update(
            table='Albums',
            columns=(
                'SingerId', 'AlbumId', 'MarketingBudget'),
            values=[
                (1, 1, 100000),
                (2, 2, 500000)])

    print('Updated data.')

Run the sample using the update_data argument.

python snippets.py test-instance --database-id example-db update_data

You can also execute a SQL query or a read call to fetch the values that you just wrote.

Here's the code to execute the query:

def query_data_with_new_column(instance_id, database_id):
    """Queries sample data from the database using SQL.

    This sample uses the `MarketingBudget` column. You can add the column
    by running the `add_column` sample or by running this DDL statement against
    your database:

        ALTER TABLE Albums ADD COLUMN MarketingBudget INT64
    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    results = database.execute_sql(
        'SELECT SingerId, AlbumId, MarketingBudget FROM Albums')

    for row in results:
        print(u'SingerId: {}, AlbumId: {}, MarketingBudget: {}'.format(*row))

To execute this query, run the sample using the query_data_with_new_column argument.

python snippets.py test-instance --database-id example-db query_data_with_new_column

You should see:

SingerId: 2, AlbumId: 2, MarketingBudget: 500000
SingerId: 1, AlbumId: 2, MarketingBudget: None
SingerId: 2, AlbumId: 1, MarketingBudget: None
SingerId: 2, AlbumId: 3, MarketingBudget: None
SingerId: 1, AlbumId: 1, MarketingBudget: 100000

Update data using a read-write transaction

Suppose that sales of Albums(1, 1) are lower than expected and you want to move $200,000 from the marketing budget of Albums(2, 2) to it, but only if the budget of Albums(2, 2) is at least $300,000.

Because this transaction might write data depending on the values read, you should use a read-write transaction to perform the reads and writes atomically.

Use the run_in_transaction() method of the Database class to run a transaction.

Here's the code to run the transaction:

def read_write_transaction(instance_id, database_id):
    """Performs a read-write transaction to update two sample records in the
    database.

    This will transfer 200,000 from the `MarketingBudget` field for the second
    Album to the first Album. If the `MarketingBudget` is too low, it will
    raise an exception.

    Before running this sample, you will need to run the `update_data` sample
    to populate the fields.
    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    def update_albums(transaction):
        # Read the second album budget.
        second_album_keyset = spanner.KeySet(keys=[(2, 2)])
        second_album_result = transaction.read(
            table='Albums', columns=('MarketingBudget',),
            keyset=second_album_keyset, limit=1)
        second_album_row = list(second_album_result)[0]
        second_album_budget = second_album_row[0]

        transfer_amount = 200000

        if second_album_budget < 300000:
            # Raising an exception will automatically roll back the
            # transaction.
            raise ValueError(
                'The second album doesn\'t have enough funds to transfer')

        # Read the first album's budget.
        first_album_keyset = spanner.KeySet(keys=[(1, 1)])
        first_album_result = transaction.read(
            table='Albums', columns=('MarketingBudget',),
            keyset=first_album_keyset, limit=1)
        first_album_row = list(first_album_result)[0]
        first_album_budget = first_album_row[0]

        # Update the budgets.
        second_album_budget -= transfer_amount
        first_album_budget += transfer_amount
        print(
            'Setting first album\'s budget to {} and the second album\'s '
            'budget to {}.'.format(
                first_album_budget, second_album_budget))

        # Update the rows.
        transaction.update(
            table='Albums',
            columns=(
                'SingerId', 'AlbumId', 'MarketingBudget'),
            values=[
                (1, 1, first_album_budget),
                (2, 2, second_album_budget)])

    database.run_in_transaction(update_albums)

    print('Transaction complete.')

Run the sample using the read_write_transaction argument.

python snippets.py test-instance --database-id example-db read_write_transaction

You should see:

Transaction complete.

Query the data again:

python snippets.py test-instance --database-id example-db query_data_with_new_column

You should see:

SingerId: 2, AlbumId: 2, MarketingBudget: 300000
SingerId: 1, AlbumId: 2, MarketingBudget: None
SingerId: 2, AlbumId: 1, MarketingBudget: None
SingerId: 2, AlbumId: 3, MarketingBudget: None
SingerId: 1, AlbumId: 1, MarketingBudget: 300000

Use a secondary index

Suppose you wanted to fetch all rows of Albums that have AlbumTitle values in a certain range. You could read all values from the AlbumTitle column using a SQL statement or a read call, and then discard the rows that don't meet the criteria, but doing this full table scan is expensive, especially for tables with a lot of rows. Instead you can speed up the retrieval of rows when searching by non-primary key columns by creating a secondary index on the table.

Adding a secondary index to an existing table requires a schema update. Like other schema updates, Cloud Spanner supports adding an index while the database continues to serve traffic. Cloud Spanner populates the index with data (aka "backfills") under the hood. Backfills might take a few minutes to complete, but you don't have to take the database offline or avoid writing to certain tables or columns during this process. For more details, see index backfilling.

Add a secondary index

You can add an index on the command line using the gcloud command line tool or programmatically using the Cloud Spanner client library for Python.

On the command line

Use the following CREATE INDEX command to add an index to the database:

gcloud spanner databases ddl update example-db --instance=test-instance \
--ddl='CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'

You should see:

DDL updating...done.

Using the Cloud Spanner client library for Python

Use the update_ddl() method of the Database class to add an index:

def add_index(instance_id, database_id):
    """Adds a simple index to the example database."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    operation = database.update_ddl([
        'CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'])

    print('Waiting for operation to complete...')
    operation.result()

    print('Added the AlbumsByAlbumTitle index.')

Run the sample using the add_index argument.

python snippets.py test-instance --database-id example-db add_index

Adding an index can take a few minutes. After the index is added, you should see:

Added the AlbumsByAlbumTitle index.

Query using the index

You can query using the new index either on the command line or using the client library.

On the command line

Execute a SQL statement using the gcloud command-line tool to fetch AlbumId, AlbumTitle, and MarketingBudget from Albums using the AlbumsByAlbumTitle index, for the range of AlbumsTitle in ["Aardvark", "Goo").

gcloud spanner databases execute-sql example-db --instance=test-instance --sql='SELECT AlbumId, AlbumTitle, MarketingBudget FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle} WHERE AlbumTitle >= "Aardvark" AND AlbumTitle < "Goo"'

The result should be:

AlbumId  AlbumTitle               MarketingBudget
2        Go, Go, Go
2        Forever Hold Your Peace  300000

Using the Cloud Spanner client library for Python

The code to programmatically use the index is similar to the query code used earlier.

def query_data_with_index(
        instance_id, database_id, start_title='Aardvark', end_title='Goo'):
    """Queries sample data from the database using SQL and an index.

    The index must exist before running this sample. You can add the index
    by running the `add_index` sample or by running this DDL statement against
    your database:

        CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)

    This sample also uses the `MarketingBudget` column. You can add the column
    by running the `add_column` sample or by running this DDL statement against
    your database:

        ALTER TABLE Albums ADD COLUMN MarketingBudget INT64

    """
    from google.cloud.proto.spanner.v1 import type_pb2

    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    params = {
        'start_title': start_title,
        'end_title': end_title
    }
    param_types = {
        'start_title': type_pb2.Type(code=type_pb2.STRING),
        'end_title': type_pb2.Type(code=type_pb2.STRING)
    }
    results = database.execute_sql(
        "SELECT AlbumId, AlbumTitle, MarketingBudget "
        "FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle} "
        "WHERE AlbumTitle >= @start_title AND AlbumTitle < @end_title",
        params=params, param_types=param_types)

    for row in results:
        print(
            u'AlbumId: {}, AlbumTitle: {}, '
            'MarketingBudget: {}'.format(*row))

Run the sample using the query_data_with_index argument.

python snippets.py test-instance --database-id example-db query_data_with_index

You should see output similar to:

AlbumId: 2, AlbumTitle: Go, Go, Go, MarketingBudget: None
AlbumId: 2, AlbumTitle: Forever Hold Your Peace, MarketingBudget: 300000

For more details, consult the reference for:

Read using the index

To read using the index, provide an Index argument to the read() method of the Database class.

def read_data_with_index(instance_id, database_id):
    """Reads sample data from the database using an index.

    The index must exist before running this sample. You can add the index
    by running the `add_index` sample or by running this DDL statement against
    your database:

        CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)

    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    keyset = spanner.KeySet(all_=True)
    results = database.read(
        table='Albums',
        columns=('AlbumId', 'AlbumTitle'),
        keyset=keyset,
        index='AlbumsByAlbumTitle')

    for row in results:
        print('AlbumId: {}, AlbumTitle: {}'.format(*row))

Run the sample using the read_data_with_index argument.

python snippets.py test-instance --database-id example-db read_data_with_index

You should see:

AlbumId: 2, AlbumTitle: Forever Hold Your Peace
AlbumId: 2, AlbumTitle: Go, Go, Go
AlbumId: 1, AlbumTitle: Green
AlbumId: 3, AlbumTitle: Terrified
AlbumId: 1, AlbumTitle: Total Junk

Add an index with a STORING clause

You might have noticed that the read example above did not include reading the MarketingBudget column. This is because Cloud Spanner's read interface does not support the ability to join an index with a data table to look up values that are not stored in the index.

Create an alternate definition of AlbumsByAlbumTitle that stores a copy of MarketingBudget in the index.

On the command line

gcloud spanner databases ddl update example-db --instance=test-instance \
--ddl='CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)'

Adding an index can take a few minutes. After the index is added, you should see:

DDL updating...done.

Using the Cloud Spanner client library for Python

Use the update_ddl() method of the Database class to add an index with a STORING clause:

def add_storing_index(instance_id, database_id):
    """Adds an storing index to the example database."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    operation = database.update_ddl([
        'CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle)'
        'STORING (MarketingBudget)'])

    print('Waiting for operation to complete...')
    operation.result()

    print('Added the AlbumsByAlbumTitle2 index.')

Run the sample using the add_storing_index argument.

python snippets.py test-instance --database-id example-db add_storing_index

You should see:

Added the AlbumsByAlbumTitle2 index.

Now you can execute a read that fetches all AlbumId, AlbumTitle, and MarketingBudget columns from the AlbumsByAlbumTitle2 index:

def read_data_with_storing_index(instance_id, database_id):
    """Reads sample data from the database using an index with a storing
    clause.

    The index must exist before running this sample. You can add the index
    by running the `add_soring_index` sample or by running this DDL statement
    against your database:

        CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle)
        STORING (MarketingBudget)

    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    keyset = spanner.KeySet(all_=True)
    results = database.read(
        table='Albums',
        columns=('AlbumId', 'AlbumTitle', 'MarketingBudget'),
        keyset=keyset,
        index='AlbumsByAlbumTitle2')

    for row in results:
        print(
            u'AlbumId: {}, AlbumTitle: {}, '
            'MarketingBudget: {}'.format(*row))

Run the sample using the read_data_with_storing_index argument.

python snippets.py test-instance --database-id example-db read_data_with_storing_index

You should see output similar to:

AlbumId: 2, AlbumTitle: Forever Hold Your Peace, MarketingBudget: 300000
AlbumId: 2, AlbumTitle: Go, Go, Go, MarketingBudget: None
AlbumId: 1, AlbumTitle: Green, MarketingBudget: None
AlbumId: 3, AlbumTitle: Terrified, MarketingBudget: None
AlbumId: 1, AlbumTitle: Total Junk, MarketingBudget: 300000

Retrieve data using read-only transactions

Suppose you want to execute more than one read at the same timestamp. Read-only transactions observe a consistent prefix of the transaction commit history, so your application always gets consistent data. Use a Snapshot object for executing read-only transactions. Use the snapshot() method of the Database class to get a Snapshot object.

The following shows how to run a query and perform a read in the same read-only transaction:

def read_only_transaction(instance_id, database_id):
    """Reads data inside of a read-only transaction.

    Within the read-only transaction, or "snapshot", the application sees
    consistent view of the database at a particular timestamp.
    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    with database.snapshot(multi_use=True) as snapshot:
        # Read using SQL.
        results = snapshot.execute_sql(
            'SELECT SingerId, AlbumId, AlbumTitle FROM Albums')

        print('Results from first read:')
        for row in results:
            print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row))

        # Perform another read using the `read` method. Even if the data
        # is updated in-between the reads, the snapshot ensures that both
        # return the same data.
        keyset = spanner.KeySet(all_=True)
        results = snapshot.read(
            table='Albums',
            columns=('SingerId', 'AlbumId', 'AlbumTitle',),
            keyset=keyset,)

        print('Results from second read:')
        for row in results:
            print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row))

Run the sample using the read_only_transaction argument.

python snippets.py test-instance --database-id example-db read_only_transaction

You should see output similar to:

Results from first read:
SingerId: 2, AlbumId: 2, AlbumTitle: Forever Hold Your Peace
SingerId: 1, AlbumId: 2, AlbumTitle: Go, Go, Go
SingerId: 2, AlbumId: 1, AlbumTitle: Green
SingerId: 2, AlbumId: 3, AlbumTitle: Terrified
SingerId: 1, AlbumId: 1, AlbumTitle: Total Junk
Results from second read:
SingerId: 1, AlbumId: 1, AlbumTitle: Total Junk
SingerId: 1, AlbumId: 2, AlbumTitle: Go, Go, Go
SingerId: 2, AlbumId: 1, AlbumTitle: Green
SingerId: 2, AlbumId: 2, AlbumTitle: Forever Hold Your Peace
SingerId: 2, AlbumId: 3, AlbumTitle: Terrified

Cleanup

To avoid incurring additional charges to your Google Cloud Platform account for the resources used in this tutorial, drop the database and delete the instance that you created.

Delete the database

If you delete an instance, all databases within it are automatically deleted. This step shows how to delete a database without deleting an instance (you would still incur charges for the instance).

On the command line

gcloud spanner databases delete example-db --instance=test-instance

Using the Cloud Platform Console

  1. Go to the Spanner Instances page in the Google Cloud Platform Console.
    Go to the Spanner Instances page
  2. Click the instance.
  3. Click the database that you want to delete.
  4. In the Database details page, click Delete.
  5. Confirm that you want to delete the database and click Delete.

Delete the instance

Deleting an instance automatically drops all databases created in that instance.

On the command line

gcloud spanner instances delete test-instance

Using the Cloud Platform Console

  1. Go to the Spanner Instances page in the Google Cloud Platform Console.
    Go to the Spanner Instances page
  2. Click your instance.
  3. Click Delete.
  4. Confirm that you want to delete the instance and click Delete.

What's next

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud Spanner Documentation