Java hello world
This code sample is a "hello world" application written in Java, using theBigtable client library for Java. The sample illustrates how to completethe following tasks:
- Set up authentication
- Connect to a Bigtable instance.
- Create a new table.
- Write data to the table.
- Read the data back.
- Delete the table.
Running the sample
This code communicates with Bigtable using the Bigtableclient library in theGoogle Cloud client libraries for Java.
Before you begin, follow the setup steps described in thereferencedocumentation.
Using the Cloud Client Libraries with Bigtable
The sample application connects to Bigtable and demonstrates somebasic operations.
Connecting to Bigtable
To get started, you need a data client that you use to communicate with thedata API client library and a table admin client that you use to communicatewith the admin API client library.
First, instantiate aBigtableDataSettings objectthat includes the project ID and instance ID that thehello world applicationwill use. Then pass the settings to theBigtableDataClient.create() method to create the data client.
Similarly, for the admin client, first establish the settings by creating aBigtableTableAdminSettings object, then usethe settings to create aBigtableTableAdminClient object.
As a best practice, when you use Bigtable you should always createa client once and reuse it throughout the application.
// Creates the settings to configure a bigtable data client.BigtableDataSettingssettings=BigtableDataSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();// Creates a bigtable data client.dataClient=BigtableDataClient.create(settings);// Creates the settings to configure a bigtable table admin client.BigtableTableAdminSettingsadminSettings=BigtableTableAdminSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();// Creates a bigtable table admin client.adminClient=BigtableTableAdminClient.create(adminSettings);Creating a table
To create a table, build aCreateTableRequest objectand pass it to the admin client'screateTable() method.
// Checks if table exists, creates table if does not exist.if(!adminClient.exists(tableId)){System.out.println("Creating table: "+tableId);CreateTableRequestcreateTableRequest=CreateTableRequest.of(tableId).addFamily(COLUMN_FAMILY);adminClient.createTable(createTableRequest);System.out.printf("Table %s created successfully%n",tableId);}Writing rows to a table
Create agreetings[] string array containing three greetings, to use asa source of data to write to the table. Loop through the array. In eachiteration of the loop, create aRowMutationobject and use thesetCell() method to add an entry to themutation.
setCell() is only called once per mutation,but you can call it up to 10,000 times per single mutation.try{System.out.println("\nWriting some greetings to the table");String[]names={"World","Bigtable","Java"};for(inti=0;i <names.length;i++){Stringgreeting="Hello "+names[i]+"!";RowMutationrowMutation=RowMutation.create(TableId.of(tableId),ROW_KEY_PREFIX+i).setCell(COLUMN_FAMILY,COLUMN_QUALIFIER_NAME,names[i]).setCell(COLUMN_FAMILY,COLUMN_QUALIFIER_GREETING,greeting);dataClient.mutateRow(rowMutation);System.out.println(greeting);}}catch(NotFoundExceptione){System.err.println("Failed to write to non-existent table: "+e.getMessage());}Reading a row by its row key
Use the data client'sreadRow() method to readthe first row that you wrote.
try{System.out.println("\nReading a single row by row key");Rowrow=dataClient.readRow(TableId.of(tableId),ROW_KEY_PREFIX+0);System.out.println("Row: "+row.getKey().toStringUtf8());for(RowCellcell:row.getCells()){System.out.printf("Family: %s Qualifier: %s Value: %s%n",cell.getFamily(),cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8());}returnrow;}catch(NotFoundExceptione){System.err.println("Failed to read from a non-existent table: "+e.getMessage());returnnull;}try{System.out.println("\nReading specific cells by family and qualifier");Rowrow=dataClient.readRow(TableId.of(tableId),ROW_KEY_PREFIX+0);System.out.println("Row: "+row.getKey().toStringUtf8());List<RowCell>cells=row.getCells(COLUMN_FAMILY,COLUMN_QUALIFIER_NAME);for(RowCellcell:cells){System.out.printf("Family: %s Qualifier: %s Value: %s%n",cell.getFamily(),cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8());}returncells;}catch(NotFoundExceptione){System.err.println("Failed to read from a non-existent table: "+e.getMessage());returnnull;}Scanning all table rows
Next, scan the entire table. Create aQuery object, pass it to thereadRows() method, and assign the results to arow stream.
try{System.out.println("\nReading the entire table");Queryquery=Query.create(TableId.of(tableId));ServerStream<Row>rowStream=dataClient.readRows(query);List<Row>tableRows=newArrayList<>();for(Rowr:rowStream){System.out.println("Row Key: "+r.getKey().toStringUtf8());tableRows.add(r);for(RowCellcell:r.getCells()){System.out.printf("Family: %s Qualifier: %s Value: %s%n",cell.getFamily(),cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8());}}returntableRows;}catch(NotFoundExceptione){System.err.println("Failed to read a non-existent table: "+e.getMessage());returnnull;}Deleting a table
Finally, delete the table with thedeleteTable() method.
System.out.println("\nDeleting table: "+tableId);try{adminClient.deleteTable(tableId);System.out.printf("Table %s deleted successfully%n",tableId);}catch(NotFoundExceptione){System.err.println("Failed to delete a non-existent table: "+e.getMessage());}Putting it all together
Here is the full code sample without comments.
packagecom.example.bigtable;import staticcom.google.cloud.bigtable.data.v2.models.Filters.FILTERS;importcom.google.api.gax.rpc.NotFoundException;importcom.google.api.gax.rpc.ServerStream;importcom.google.cloud.bigtable.admin.v2.BigtableTableAdminClient;importcom.google.cloud.bigtable.admin.v2.BigtableTableAdminSettings;importcom.google.cloud.bigtable.admin.v2.models.CreateTableRequest;importcom.google.cloud.bigtable.data.v2.BigtableDataClient;importcom.google.cloud.bigtable.data.v2.BigtableDataSettings;importcom.google.cloud.bigtable.data.v2.models.Filters.Filter;importcom.google.cloud.bigtable.data.v2.models.Query;importcom.google.cloud.bigtable.data.v2.models.Row;importcom.google.cloud.bigtable.data.v2.models.RowCell;importcom.google.cloud.bigtable.data.v2.models.RowMutation;importcom.google.cloud.bigtable.data.v2.models.TableId;importjava.io.IOException;importjava.nio.charset.StandardCharsets;importjava.util.ArrayList;importjava.util.Base64;importjava.util.List;publicclassHelloWorld{privatestaticfinalStringCOLUMN_FAMILY="cf1";privatestaticfinalStringCOLUMN_QUALIFIER_GREETING="greeting";privatestaticfinalStringCOLUMN_QUALIFIER_NAME="name";privatestaticfinalStringROW_KEY_PREFIX="rowKey";privatefinalStringtableId;privatefinalBigtableDataClientdataClient;privatefinalBigtableTableAdminClientadminClient;publicstaticvoidmain(String[]args)throwsException{if(args.length!=2){System.out.println("Missing required project id or instance id");return;}StringprojectId=args[0];StringinstanceId=args[1];HelloWorldhelloWorld=newHelloWorld(projectId,instanceId,"test-table");helloWorld.run();}publicHelloWorld(StringprojectId,StringinstanceId,StringtableId)throwsIOException{this.tableId=tableId;BigtableDataSettingssettings=BigtableDataSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();dataClient=BigtableDataClient.create(settings);BigtableTableAdminSettingsadminSettings=BigtableTableAdminSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();adminClient=BigtableTableAdminClient.create(adminSettings);}publicvoidrun()throwsException{createTable();writeToTable();readSingleRow();readSpecificCells();readTable();filterLimitCellsPerCol(tableId);deleteTable();close();}publicvoidclose(){dataClient.close();adminClient.close();}publicvoidcreateTable(){if(!adminClient.exists(tableId)){System.out.println("Creating table: "+tableId);CreateTableRequestcreateTableRequest=CreateTableRequest.of(tableId).addFamily(COLUMN_FAMILY);adminClient.createTable(createTableRequest);System.out.printf("Table %s created successfully%n",tableId);}}publicvoidwriteToTable(){try{System.out.println("\nWriting some greetings to the table");String[]names={"World","Bigtable","Java"};for(inti=0;i <names.length;i++){Stringgreeting="Hello "+names[i]+"!";RowMutationrowMutation=RowMutation.create(TableId.of(tableId),ROW_KEY_PREFIX+i).setCell(COLUMN_FAMILY,COLUMN_QUALIFIER_NAME,names[i]).setCell(COLUMN_FAMILY,COLUMN_QUALIFIER_GREETING,greeting);dataClient.mutateRow(rowMutation);System.out.println(greeting);}}catch(NotFoundExceptione){System.err.println("Failed to write to non-existent table: "+e.getMessage());}}publicRowreadSingleRow(){try{System.out.println("\nReading a single row by row key");Rowrow=dataClient.readRow(TableId.of(tableId),ROW_KEY_PREFIX+0);System.out.println("Row: "+row.getKey().toStringUtf8());for(RowCellcell:row.getCells()){System.out.printf("Family: %s Qualifier: %s Value: %s%n",cell.getFamily(),cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8());}returnrow;}catch(NotFoundExceptione){System.err.println("Failed to read from a non-existent table: "+e.getMessage());returnnull;}}publicList<RowCell>readSpecificCells(){try{System.out.println("\nReading specific cells by family and qualifier");Rowrow=dataClient.readRow(TableId.of(tableId),ROW_KEY_PREFIX+0);System.out.println("Row: "+row.getKey().toStringUtf8());List<RowCell>cells=row.getCells(COLUMN_FAMILY,COLUMN_QUALIFIER_NAME);for(RowCellcell:cells){System.out.printf("Family: %s Qualifier: %s Value: %s%n",cell.getFamily(),cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8());}returncells;}catch(NotFoundExceptione){System.err.println("Failed to read from a non-existent table: "+e.getMessage());returnnull;}}publicList<Row>readTable(){try{System.out.println("\nReading the entire table");Queryquery=Query.create(TableId.of(tableId));ServerStream<Row>rowStream=dataClient.readRows(query);List<Row>tableRows=newArrayList<>();for(Rowr:rowStream){System.out.println("Row Key: "+r.getKey().toStringUtf8());tableRows.add(r);for(RowCellcell:r.getCells()){System.out.printf("Family: %s Qualifier: %s Value: %s%n",cell.getFamily(),cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8());}}returntableRows;}catch(NotFoundExceptione){System.err.println("Failed to read a non-existent table: "+e.getMessage());returnnull;}}publicvoidfilterLimitCellsPerCol(StringtableId){Filterfilter=FILTERS.limit().cellsPerColumn(1);readRowFilter(tableId,filter);readFilter(tableId,filter);}privatevoidreadRowFilter(StringtableId,Filterfilter){StringrowKey=Base64.getEncoder().encodeToString("greeting0".getBytes(StandardCharsets.UTF_8));Rowrow=dataClient.readRow(TableId.of(tableId),rowKey,filter);printRow(row);System.out.println("Row filter completed.");}privatevoidreadFilter(StringtableId,Filterfilter){Queryquery=Query.create(TableId.of(tableId)).filter(filter);ServerStream<Row>rows=dataClient.readRows(query);for(Rowrow:rows){printRow(row);}System.out.println("Table filter completed.");}publicvoiddeleteTable(){System.out.println("\nDeleting table: "+tableId);try{adminClient.deleteTable(tableId);System.out.printf("Table %s deleted successfully%n",tableId);}catch(NotFoundExceptione){System.err.println("Failed to delete a non-existent table: "+e.getMessage());}}privatestaticvoidprintRow(Rowrow){if(row==null){return;}System.out.printf("Reading data for %s%n",row.getKey().toStringUtf8());StringcolFamily="";for(RowCellcell:row.getCells()){if(!cell.getFamily().equals(colFamily)){colFamily=cell.getFamily();System.out.printf("Column Family %s%n",colFamily);}Stringlabels=cell.getLabels().size()==0?"":" ["+String.join(",",cell.getLabels())+"]";System.out.printf("\t%s: %s @%s%s%n",cell.getQualifier().toStringUtf8(),cell.getValue().toStringUtf8(),cell.getTimestamp(),labels);}System.out.println();}}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 2025-12-15 UTC.