Java hello world
This code sample is a "hello world" application written in Java, using the Bigtable client library for Java. The sample illustrates how to complete the 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 Bigtable client library in the Google Cloud client libraries for Java.
Before you begin, follow the setup steps described in the reference documentation.
Using the Cloud Client Libraries with Bigtable
The sample application connects to Bigtable and demonstrates some basic operations.
Connecting to Bigtable
To get started, you need a data client that you use to communicate with the data API client library and a table admin client that you use to communicate with the admin API client library.
First, instantiate a BigtableDataSettings
object
that includes the project ID and instance ID that the hello world
application
will use. Then pass the settings to the BigtableDataClient.create()
method to create the data client.
Similarly, for the admin client, first establish the settings by creating a
BigtableTableAdminSettings
object, then use
the settings to create a BigtableTableAdminClient
object.
As a best practice, when you use Bigtable you should always create a client once and reuse it throughout the application.
Creating a table
To create a table, build a CreateTableRequest
object
and pass it to the admin client's createTable()
method.
Writing rows to a table
Create a greetings[]
string array containing three greetings, to use as
a source of data to write to the table. Loop through the array. In each
iteration of the loop, create a RowMutation
object and use the setCell()
method to add an entry to the
mutation.
Reading a row by its row key
Use the data client's readRow()
method to read
the first row that you wrote.
Scanning all table rows
Next, scan the entire table. Create a Query
object, pass it to the
readRows()
method, and assign the results to a
row stream.
Deleting a table
Finally, delete the table with the deleteTable()
method.
Putting it all together
Here is the full code sample without comments.