Example: Python "Hello World" Application

This example is a very simple "hello world" application, written in Python, that illustrates how to:

  • Connect to a Cloud Bigtable instance.
  • Create a new table.
  • Write data to the table.
  • Read the data back.
  • Delete the table.

Running the sample

This example uses the Cloud Bigtable package of the Google Cloud Client Library for Python to communicate with Cloud Bigtable. The Cloud Bigtable package is the best choice for new applications. If you need to move an existing HBase workload to Cloud Bigtable, see the "hello world" example that uses the HappyBase package.

To run this sample program, follow the instructions for the sample on GitHub.

Using the Cloud Client Library with Cloud Bigtable

The sample application connects to Cloud Bigtable and demonstrates some simple operations.

Installing and importing the client library

The required Python packages can be installed using PIP into a virtualenv environment. The sample includes a requirements file defining the needed packages.

google-cloud-bigtable==0.20.0

The modules can then be imported.

from google.cloud import bigtable

Connecting to Cloud Bigtable

Connect to Cloud Bigtable using a bigtable.Client.

# The client must be created with admin=True because it will create a
# table.
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(instance_id)

Creating a table

Describe the table using Instance.table(), then create it with Table.create(). A column family can be created with Table.column_family() followed by a call to ColumnFamily.create().

print('Creating the {} table.'.format(table_id))
table = instance.table(table_id)
table.create()
column_family_id = 'cf1'
cf1 = table.column_family(column_family_id)
cf1.create()

Writing rows to a table

Use Table.row() to define a row, then set values on the row with DirectRow.set_cell(). Finally, call DirectRow.commit() to add the row to the table.

print('Writing some greetings to the table.')
column_id = 'greeting'.encode('utf-8')
greetings = [
    'Hello World!',
    'Hello Cloud Bigtable!',
    'Hello Python!',
]

for i, value in enumerate(greetings):
    # Note: This example uses sequential numeric IDs for simplicity,
    # but this can result in poor performance in a production
    # application.  Since rows are stored in sorted order by key,
    # sequential keys can result in poor distribution of operations
    # across nodes.
    #
    # For more information about how to design a Bigtable schema for
    # the best performance, see the documentation:
    #
    #     https://cloud.google.com/bigtable/docs/schema-design
    row_key = 'greeting{}'.format(i)
    row = table.row(row_key)
    row.set_cell(
        column_family_id,
        column_id,
        value.encode('utf-8'))
    row.commit()

Reading a row by its key

Get a row directly using its key with Table.read_row().

print('Getting a single greeting by row key.')
key = 'greeting0'
row = table.read_row(key.encode('utf-8'))
value = row.cells[column_family_id][column_id][0].value
print('\t{}: {}'.format(key, value.decode('utf-8')))

Scanning all table rows

Use the Table.read_rows() to get a range of rows from a table. Call PartialRowsData.consume_all() to fill the PartialRowsData.rows dictionary.

print('Scanning for all greetings:')
partial_rows = table.read_rows()
partial_rows.consume_all()

for row_key, row in partial_rows.rows.items():
    key = row_key.decode('utf-8')
    cell = row.cells[column_family_id][column_id][0]
    value = cell.value.decode('utf-8')
    print('\t{}: {}'.format(key, value))

Deleting a table

Delete a table with Table.delete().

print('Deleting the {} table.'.format(table_id))
table.delete()

Putting it all together

Here is the full example without comments.


"""Demonstrates how to connect to Cloud Bigtable and run some basic operations.

Prerequisites:

- Create a Cloud Bigtable cluster.
  https://cloud.google.com/bigtable/docs/creating-cluster
- Set your Google Application Default Credentials.
  https://developers.google.com/identity/protocols/application-default-credentials
"""

import argparse

from google.cloud import bigtable


def main(project_id, instance_id, table_id):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)

    print('Creating the {} table.'.format(table_id))
    table = instance.table(table_id)
    table.create()
    column_family_id = 'cf1'
    cf1 = table.column_family(column_family_id)
    cf1.create()

    print('Writing some greetings to the table.')
    column_id = 'greeting'.encode('utf-8')
    greetings = [
        'Hello World!',
        'Hello Cloud Bigtable!',
        'Hello Python!',
    ]

    for i, value in enumerate(greetings):
        row_key = 'greeting{}'.format(i)
        row = table.row(row_key)
        row.set_cell(
            column_family_id,
            column_id,
            value.encode('utf-8'))
        row.commit()

    print('Getting a single greeting by row key.')
    key = 'greeting0'
    row = table.read_row(key.encode('utf-8'))
    value = row.cells[column_family_id][column_id][0].value
    print('\t{}: {}'.format(key, value.decode('utf-8')))

    print('Scanning for all greetings:')
    partial_rows = table.read_rows()
    partial_rows.consume_all()

    for row_key, row in partial_rows.rows.items():
        key = row_key.decode('utf-8')
        cell = row.cells[column_family_id][column_id][0]
        value = cell.value.decode('utf-8')
        print('\t{}: {}'.format(key, value))

    print('Deleting the {} table.'.format(table_id))
    table.delete()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('project_id', help='Your Cloud Platform project ID.')
    parser.add_argument(
        'instance_id', help='ID of the Cloud Bigtable instance to connect to.')
    parser.add_argument(
        '--table',
        help='Table to create and destroy.',
        default='Hello-Bigtable')

    args = parser.parse_args()
    main(args.project_id, args.instance_id, args.table)

Send feedback about...

Cloud Bigtable Documentation