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.
Set up authentication
To use the Java 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.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
For more information, see Set up authentication for a local development environment.
Running the sample
This code communicates with Bigtable using the Google Cloud Bigtable library in the Google Cloud Client Libraries for Java.
Follow the Google Cloud Platform Samples instructions on GitHub before you get started.
Using the Cloud Client Library with Bigtable
The sample application connects to Bigtable and demonstrates some simple 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 simple 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.