Example: C++ "Hello World" Application

This example is a simple "hello world" application, written in C++, that illustrates how to do the following:

  • 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 C++ to communicate with Cloud Bigtable.

To run this sample program, follow the instructions 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

Download or clone the Cloud Bigtable C++ client library from GitHub, then compile it. Follow the compiler instructions on the top-level README.

Include the required headers.

#include "google/cloud/bigtable/table.h"
#include "google/cloud/bigtable/table_admin.h"

Connecting to Cloud Bigtable

Use TableAdmin.CreateDefaultAdminClient() to create an admin client that you will use to create a table.

cbt::TableAdmin table_admin(
    cbt::CreateDefaultAdminClient(project_id, cbt::ClientOptions()),
    instance_id);

Creating a table

Define a schema for the table that has one column family. Set a garbage-collection rule for the column family to keep a maximum of one version of each value. Use that schema to instantiate a table object using TableAdmin.CreateTable(). Then create a data client that you can use to get data in and out of your table.

// Define the desired schema for the Table.
cbt::GcRule gc_rule = cbt::GcRule::MaxNumVersions(1);
cbt::TableConfig schema({{"family", gc_rule}}, {});

// Create a table.
StatusOr<google::bigtable::admin::v2::Table> returned_schema =
    table_admin.CreateTable(table_id, schema);

// Create an object to access the Cloud Bigtable Data API.
cbt::Table table(cbt::CreateDefaultDataClient(project_id, instance_id,
                                              cbt::ClientOptions()),
                 table_id);

Writing rows to a table

Loop through a list of greeting strings to create some new rows for the table. In each iteration, use SingleRowMutation() to define a row and assign it a row key and value. Then call Table.Apply() to apply the mutation to the row.

std::vector<std::string> greetings{"Hello World!", "Hello Cloud Bigtable!",
                                   "Hello C++!"};
int i = 0;
for (auto const& greeting : greetings) {
  // Each row has a unique row key.
  //
  // 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
  std::string row_key = "key-" + std::to_string(i);
  google::cloud::Status status = table.Apply(cbt::SingleRowMutation(
      std::move(row_key), cbt::SetCell("family", "c0", greeting)));

  if (!status.ok()) {
    throw std::runtime_error(status.message());
  }
  ++i;
}

Creating a filter

Before you read the data that you wrote, create a filter, using Filter.ColumnRangeClosed(), to limit the data that Cloud Bigtable returns. This filter tells Cloud Bigtable to return only the most recent version of each value, even if the table contains older versions that haven't been garbage-collected.

cbt::Filter filter = cbt::Filter::ColumnRangeClosed("family", "c0", "c0");

Reading a row by its key

Call the Table.ReadRow() function, passing in the row key and the filter, to get one version of each value in that row.

StatusOr<std::pair<bool, cbt::Row>> result = table.ReadRow("key-0", filter);
if (!result) {
  throw std::runtime_error(result.status().message());
}
if (!result->first) {
  std::cout << "Cannot find row 'key-0' in the table: " << table.table_name()
            << "\n";
  return 0;
}
cbt::Cell const& cell = result->second.cells().front();
std::cout << cell.family_name() << ":" << cell.column_qualifier() << "    @ "
          << cell.timestamp().count() << "us\n"
          << '"' << cell.value() << '"' << "\n";

Scanning all table rows

Use Table.ReadRows() to read a range of rows from the table.

for (StatusOr<cbt::Row> const& row : table.ReadRows(
         cbt::RowRange::InfiniteRange(), cbt::Filter::PassAllFilter())) {
  if (!row) {
    throw std::runtime_error(row.status().message());
  }
  std::cout << row->row_key() << ":\n";
  for (cbt::Cell const& cell : row->cells()) {
    std::cout << "\t" << cell.family_name() << ":" << cell.column_qualifier()
              << "    @ " << cell.timestamp().count() << "us\n"
              << "\t\"" << cell.value() << '"' << "\n";
  }
}

Deleting a table

Delete the table with DeleteTable().

google::cloud::Status status = table_admin.DeleteTable(table_id);
if (!status.ok()) {
  throw std::runtime_error(status.message());
}

Putting it all together

Here is the full example without comments.


#include "google/cloud/bigtable/table.h"
#include "google/cloud/bigtable/table_admin.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 4) {
    std::string const cmd = argv[0];
    auto last_slash = std::string(cmd).find_last_of('/');
    std::cerr << "Usage: " << cmd.substr(last_slash + 1)
              << " <project_id> <instance_id> <table_id>\n";
    return 1;
  }

  std::string const project_id = argv[1];
  std::string const instance_id = argv[2];
  std::string const table_id = argv[3];

  namespace cbt = google::cloud::bigtable;
  using google::cloud::StatusOr;

  cbt::TableAdmin table_admin(
      cbt::CreateDefaultAdminClient(project_id, cbt::ClientOptions()),
      instance_id);

  cbt::GcRule gc_rule = cbt::GcRule::MaxNumVersions(1);
  cbt::TableConfig schema({{"family", gc_rule}}, {});

  StatusOr<google::bigtable::admin::v2::Table> returned_schema =
      table_admin.CreateTable(table_id, schema);

  cbt::Table table(cbt::CreateDefaultDataClient(project_id, instance_id,
                                                cbt::ClientOptions()),
                   table_id);

  std::vector<std::string> greetings{"Hello World!", "Hello Cloud Bigtable!",
                                     "Hello C++!"};
  int i = 0;
  for (auto const& greeting : greetings) {
    std::string row_key = "key-" + std::to_string(i);
    google::cloud::Status status = table.Apply(cbt::SingleRowMutation(
        std::move(row_key), cbt::SetCell("family", "c0", greeting)));

    if (!status.ok()) {
      throw std::runtime_error(status.message());
    }
    ++i;
  }

  cbt::Filter filter = cbt::Filter::ColumnRangeClosed("family", "c0", "c0");

  StatusOr<std::pair<bool, cbt::Row>> result = table.ReadRow("key-0", filter);
  if (!result) {
    throw std::runtime_error(result.status().message());
  }
  if (!result->first) {
    std::cout << "Cannot find row 'key-0' in the table: " << table.table_name()
              << "\n";
    return 0;
  }
  cbt::Cell const& cell = result->second.cells().front();
  std::cout << cell.family_name() << ":" << cell.column_qualifier() << "    @ "
            << cell.timestamp().count() << "us\n"
            << '"' << cell.value() << '"' << "\n";

  for (StatusOr<cbt::Row> const& row : table.ReadRows(
           cbt::RowRange::InfiniteRange(), cbt::Filter::PassAllFilter())) {
    if (!row) {
      throw std::runtime_error(row.status().message());
    }
    std::cout << row->row_key() << ":\n";
    for (cbt::Cell const& cell : row->cells()) {
      std::cout << "\t" << cell.family_name() << ":" << cell.column_qualifier()
                << "    @ " << cell.timestamp().count() << "us\n"
                << "\t\"" << cell.value() << '"' << "\n";
    }
  }

  google::cloud::Status status = table_admin.DeleteTable(table_id);
  if (!status.ok()) {
    throw std::runtime_error(status.message());
  }

  return 0;
} catch (std::exception const& ex) {
  std::cerr << "Standard C++ exception raised: " << ex.what() << "\n";
  return 1;
}
Oliko tästä sivusta apua? Kerro mielipiteesi

Palautteen aihe:

Tämä sivu
Cloud Bigtable Documentation