Cloud Functions quickstart

Use Bigtable within a Cloud Functions.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

C++

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

#include <google/cloud/bigtable/table.h>
#include <google/cloud/functions/http_request.h>
#include <google/cloud/functions/http_response.h>
#include <algorithm>
#include <cctype>
#include <mutex>
#include <sstream>
#include <string>

namespace gcf = ::google::cloud::functions;
namespace cbt = ::google::cloud::bigtable;

cbt::Table get_table_client(std::string project_id, std::string instance_id,
                            std::string const& table_id) {
  static std::mutex mu;
  static std::unique_ptr<cbt::Table> table;
  std::lock_guard lk(mu);
  if (table == nullptr || table->table_id() != table_id ||
      table->instance_id() != instance_id ||
      table->project_id() != project_id) {
    table = std::make_unique<cbt::Table>(
        cbt::CreateDefaultDataClient(std::move(project_id),
                                     std::move(instance_id),
                                     cbt::ClientOptions{}),
        table_id);
  }
  return *table;
}

gcf::HttpResponse tutorial_cloud_bigtable(gcf::HttpRequest request) {  // NOLINT
  auto get_header = [h = request.headers()](std::string key) {
    std::transform(key.begin(), key.end(), key.begin(),
                   [](auto x) { return static_cast<char>(std::tolower(x)); });
    auto l = h.find(key);
    if (l == h.end()) throw std::invalid_argument("Missing header: " + key);
    return l->second;
  };

  auto project_id = get_header("projectID");
  auto instance_id = get_header("instanceID");
  auto table_id = get_header("tableID");
  auto table =
      get_table_client(std::move(project_id), std::move(instance_id), table_id);

  std::ostringstream os;
  auto filter =
      cbt::Filter::Chain(cbt::Filter::Latest(1),
                         cbt::Filter::ColumnName("stats_summary", "os_build"));
  for (auto row : table.ReadRows(cbt::RowRange::Prefix("phone#"), filter)) {
    if (!row) {
      std::ostringstream err;
      err << "Error reading from bigtable: " << row.status();
      throw std::runtime_error(std::move(err).str());
    }
    for (auto const& cell : row->cells()) {
      os << "Rowkey: " << cell.row_key() << ", os_build: " << cell.value()
         << "\n";
    }
  }

  return gcf::HttpResponse{}
      .set_header("content-type", "text/plain")
      .set_payload(std::move(os).str());
}

Go

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.


// Package bigtable contains an example of using Bigtable from a Cloud Function.
package bigtable

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"sync"

	"cloud.google.com/go/bigtable"
)

// client is a global Bigtable client, to avoid initializing a new client for
// every request.
var client *bigtable.Client
var clientOnce sync.Once

// BigtableRead is an example of reading Bigtable from a Cloud Function.
func BigtableRead(w http.ResponseWriter, r *http.Request) {
	clientOnce.Do(func() {
		// Declare a separate err variable to avoid shadowing client.
		var err error
		client, err = bigtable.NewClient(context.Background(), r.Header.Get("projectID"), r.Header.Get("instanceId"))
		if err != nil {
			http.Error(w, "Error initializing client", http.StatusInternalServerError)
			log.Printf("bigtable.NewClient: %v", err)
			return
		}
	})

	tbl := client.Open(r.Header.Get("tableID"))
	err := tbl.ReadRows(r.Context(), bigtable.PrefixRange("phone#"),
		func(row bigtable.Row) bool {
			osBuild := ""
			for _, col := range row["stats_summary"] {
				if col.Column == "stats_summary:os_build" {
					osBuild = string(col.Value)
				}
			}

			fmt.Fprintf(w, "Rowkey: %s, os_build:  %s\n", row.Key(), osBuild)
			return true
		})

	if err != nil {
		http.Error(w, "Error reading rows", http.StatusInternalServerError)
		log.Printf("tbl.ReadRows(): %v", err)
	}
}

Node.js

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

// Imports the Google Cloud client library
const {Bigtable} = require('@google-cloud/bigtable');

// Instantiates a client
const bigtable = new Bigtable();

exports.readRows = async (req, res) => {
  // Gets a reference to a Cloud Bigtable instance and database
  const instance = bigtable.instance(req.body.instanceId);
  const table = instance.table(req.body.tableId);

  // Execute the query
  try {
    const prefix = 'phone#';
    const rows = [];
    await table
      .createReadStream({
        prefix,
      })
      .on('error', err => {
        res.send(`Error querying Bigtable: ${err}`);
        res.status(500).end();
      })
      .on('data', row => {
        rows.push(
          `rowkey: ${row.id}, ` +
            `os_build: ${row.data['stats_summary']['os_build'][0].value}\n`
        );
      })
      .on('end', () => {
        rows.forEach(r => res.write(r));
        res.status(200).end();
      });
  } catch (err) {
    res.send(`Error querying Bigtable: ${err}`);
    res.status(500).end();
  }
};

Python

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

from google.cloud import bigtable
from google.cloud.bigtable.row_set import RowSet

client = bigtable.Client()


def bigtable_read_data(request):
    instance = client.instance(request.headers.get("instance_id"))
    table = instance.table(request.headers.get("table_id"))

    prefix = 'phone#'
    end_key = prefix[:-1] + chr(ord(prefix[-1]) + 1)

    outputs = []
    row_set = RowSet()
    row_set.add_row_range_from_keys(prefix.encode("utf-8"),
                                    end_key.encode("utf-8"))

    rows = table.read_rows(row_set=row_set)
    for row in rows:
        output = 'Rowkey: {}, os_build: {}'.format(
            row.row_key.decode('utf-8'),
            row.cells["stats_summary"]["os_build".encode('utf-8')][0]
            .value.decode('utf-8'))
        outputs.append(output)

    return '\n'.join(outputs)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.