Python hello world
This example is a "hello world" application, written in Python, thatillustrates how to do the following:
- Set up authentication.
- Connect to a Bigtable instance.
- Create a new table.
- Write data to the table.
- Read the data back.
- Delete the table.
The Python client library for Bigtable offers two APIs,asyncioand a synchronous API. If your application is asynchronous, useasyncio.
Set up authentication
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Run the sample
This example uses theBigtable packageof theCloud Client Libraries for Python to communicatewith Bigtable. The Bigtable package is the bestchoice for new applications. If you need to move an existing HBase workload toBigtable, see the"hello world" example that uses the HappyBasepackage.
To run this sample program, follow theinstructions for the sample onGitHub.
Use the Cloud Client Libraries with Bigtable
The sample application connects to Bigtable and demonstrates someoperations.
Install and import the client library
UsePIP to install the required Python packages into avirtualenv environment. The sample includes arequirementsfile defining the needed packages.
google-cloud-bigtable==2.35.0google-cloud-core==2.5.0Import the modules.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
fromgoogle.cloudimportbigtablefromgoogle.cloud.bigtable.dataimportrow_filtersSync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
fromdatetimeimportdatetime,timezonefromgoogle.cloudimportbigtablefromgoogle.cloud.bigtableimportcolumn_familyfromgoogle.cloud.bigtableimportrow_filtersConnect to Bigtable
Connect to Bigtable using abigtable.Client.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
client=bigtable.data.BigtableDataClientAsync(project=project_id)table=client.get_table(instance_id,table_id)Sync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
# 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)Create a table
Instantiate a table object usingInstance.table(). Create a column family and set itsgarbage collection policy, then pass the column family toTable.create() to create the table.
print("Creating the{} table.".format(table_id))table=instance.table(table_id)print("Creating column family cf1 with Max Version GC rule...")# Create a column family with GC policy : most recent N versions# Define the GC policy to retain only the most recent 2 versionsmax_versions_rule=bigtable.column_family.MaxVersionsGCRule(2)column_family_id=b"cf1"column_families={column_family_id:max_versions_rule}ifnottable.exists():table.create(column_families=column_families)else:print("Table{} already exists.".format(table_id))Write rows to a table
Loop through a list of greeting strings to create some new rows for the table.In each iteration, useTable.row() to define a rowand assign it a row key; callRow.set_cell() toset a value for the current cell; and append the new row to an array of rows.Finally, callTable.mutate_rows() to addthe rows to the table.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
print("Writing some greetings to the table.")greetings=[b"Hello World!",b"Hello Cloud Bigtable!",b"Hello Python!"]mutations=[]column=b"greeting"fori,valueinenumerate(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.## We recommend that you use bytestrings directly for row keys# where possible, rather than encoding strings.## For more information about how to design a Bigtable schema for# the best performance, see the documentation:## https://cloud.google.com/bigtable/docs/schema-designrow_key=f"greeting{i}".encode()row_mutation=bigtable.data.RowMutationEntry(row_key,bigtable.data.SetCell(column_family_id,column,value))mutations.append(row_mutation)awaittable.bulk_mutate_rows(mutations)Sync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
print("Writing some greetings to the table.")greetings=[b"Hello World!",b"Hello Cloud Bigtable!",b"Hello Python!"]rows=[]column=b"greeting"fori,valueinenumerate(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.## We recommend that you use bytestrings directly for row keys# where possible, rather than encoding strings.## For more information about how to design a Bigtable schema for# the best performance, see the documentation:## https://cloud.google.com/bigtable/docs/schema-designrow_key=f"greeting{i}".encode()row=table.direct_row(row_key)row.set_cell(column_family_id,column,value,timestamp=datetime.now(timezone.utc),)rows.append(row)table.mutate_rows(rows)Create a filter
Before you read the data that you wrote, create a filter usingrow_filters.CellsColumnLimitFilter() to limit the data thatBigtable returns. This filter tells Bigtable toreturn only the most recent cell in each column, even if the table containsolder cells that haven't been removed yet during garbage collection.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
# Create a filter to only retrieve the most recent version of the cell# for each column across entire row.row_filter=bigtable.data.row_filters.CellsColumnLimitFilter(1)Sync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
row_filter=bigtable.row_filters.CellsColumnLimitFilter(1)Read a row by its row key
Call the table'sTable.read_row() method to get a reference tothe row with a specific row key, passing in the key and the filter, to get oneversion of each value in that row.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
print("Getting a single greeting by row key.")key="greeting0".encode()row=awaittable.read_row(key,row_filter=row_filter)cell=row.cells[0]print(cell.value.decode("utf-8"))Sync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
print("Getting a single greeting by row key.")key=b"greeting0"row=table.read_row(key,row_filter)cell=row.cells[column_family_id.decode("utf-8")][column][0]print(cell.value.decode("utf-8"))Scan all table rows
UseTable.read_rows() to read a range of rowsfrom a table.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
print("Scanning for all greetings:")query=bigtable.data.ReadRowsQuery(row_filter=row_filter)asyncforrowinawaittable.read_rows_stream(query):cell=row.cells[0]print(cell.value.decode("utf-8"))Sync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
print("Scanning for all greetings:")partial_rows=table.read_rows(filter_=row_filter)forrowinpartial_rows:column_family_id_str=column_family_id.decode("utf-8")cell=row.cells[column_family_id_str][column][0]print(cell.value.decode("utf-8"))Delete a table
Delete a table withTable.delete().
print("Deleting the{} table.".format(table_id))table.delete()Put it all together
Here is the full example without comments.
Asyncio
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
"""Demonstrates how to connect to Cloud Bigtable and run some basic operations with the async APIsPrerequisites:- Create a Cloud Bigtable instance. https://cloud.google.com/bigtable/docs/creating-instance- Set your Google Application Default Credentials. https://developers.google.com/identity/protocols/application-default-credentials"""importargparseimportasynciofrom..utilsimportwait_for_tablefromgoogle.cloudimportbigtablefromgoogle.cloud.bigtable.dataimportrow_filtersrow_filtersasyncdefmain(project_id,instance_id,table_id):client=bigtable.data.BigtableDataClientAsync(project=project_id)table=client.get_table(instance_id,table_id)fromgoogle.cloud.bigtableimportcolumn_familyprint("Creating the{} table.".format(table_id))admin_client=bigtable.Client(project=project_id,admin=True)admin_instance=admin_client.instance(instance_id)admin_table=admin_instance.table(table_id)print("Creating column family cf1 with Max Version GC rule...")max_versions_rule=column_family.MaxVersionsGCRule(2)column_family_id=b"cf1"column_families={column_family_id:max_versions_rule}ifnotadmin_table.exists():admin_table.create(column_families=column_families)else:print("Table{} already exists.".format(table_id))try:wait_for_table(admin_table)print("Writing some greetings to the table.")greetings=[b"Hello World!",b"Hello Cloud Bigtable!",b"Hello Python!"]mutations=[]column=b"greeting"fori,valueinenumerate(greetings):row_key=f"greeting{i}".encode()row_mutation=bigtable.data.RowMutationEntry(row_key,bigtable.data.SetCell(column_family_id,column,value))mutations.append(row_mutation)awaittable.bulk_mutate_rows(mutations)row_filter=bigtable.data.row_filters.CellsColumnLimitFilter(1)print("Getting a single greeting by row key.")key="greeting0".encode()row=awaittable.read_row(key,row_filter=row_filter)cell=row.cells[0]print(cell.value.decode("utf-8"))print("Scanning for all greetings:")query=bigtable.data.ReadRowsQuery(row_filter=row_filter)asyncforrowinawaittable.read_rows_stream(query):cell=row.cells[0]print(cell.value.decode("utf-8"))finally:print("Deleting the{} table.".format(table_id))admin_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()asyncio.run(main(args.project_id,args.instance_id,args.table))Sync
To learn how to install and use the client library for Bigtable, seeBigtable client libraries.
To authenticate to Bigtable, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
"""Demonstrates how to connect to Cloud Bigtable and run some basic operations.Prerequisites:- Create a Cloud Bigtable instance. https://cloud.google.com/bigtable/docs/creating-instance- Set your Google Application Default Credentials. https://developers.google.com/identity/protocols/application-default-credentials"""importargparsefrom..utilsimportwait_for_tablefromdatetimeimportdatetime,timezonefromgoogle.cloudimportbigtablefromgoogle.cloud.bigtableimportcolumn_familyfromgoogle.cloud.bigtableimportrow_filtersrow_filterscolumn_familydefmain(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)print("Creating column family cf1 with Max Version GC rule...")max_versions_rule=bigtable.column_family.MaxVersionsGCRule(2)column_family_id=b"cf1"column_families={column_family_id:max_versions_rule}ifnottable.exists():table.create(column_families=column_families)else:print("Table{} already exists.".format(table_id))try:wait_for_table(table)print("Writing some greetings to the table.")greetings=[b"Hello World!",b"Hello Cloud Bigtable!",b"Hello Python!"]rows=[]column=b"greeting"fori,valueinenumerate(greetings):row_key=f"greeting{i}".encode()row=table.direct_row(row_key)row.set_cell(column_family_id,column,value,timestamp=datetime.now(timezone.utc),)rows.append(row)table.mutate_rows(rows)row_filter=bigtable.row_filters.CellsColumnLimitFilter(1)print("Getting a single greeting by row key.")key=b"greeting0"row=table.read_row(key,row_filter)cell=row.cells[column_family_id.decode("utf-8")][column][0]print(cell.value.decode("utf-8"))print("Scanning for all greetings:")partial_rows=table.read_rows(filter_=row_filter)forrowinpartial_rows:column_family_id_str=column_family_id.decode("utf-8")cell=row.cells[column_family_id_str][column][0]print(cell.value.decode("utf-8"))finally: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)Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.