Node.js Hello World

Esse exemplo de código é um aplicativo "hello world" que é executado no Node.js. Ela mostra como concluir as seguintes tarefas:

  • Configurar a autenticação
  • Conectar-se a uma instância do Bigtable.
  • criar uma nova tabela;
  • Gravação de dados na tabela
  • Leitura dos dados
  • Exclusão da tabela

Configurar a autenticação

Para usar as amostras de Node.js nesta página de um ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure o Application Default Credentials com as credenciais de usuário.

  1. Instale a CLI do Google Cloud.
  2. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  3. Crie as credenciais de autenticação para sua Conta do Google:

    gcloud auth application-default login

Veja mais informações em: Configurar a autenticação para um ambiente de desenvolvimento local.

Como executar a amostra

Este exemplo de código usa o pacote do Bigtable da biblioteca de cliente do Google Cloud para Node.js na comunicação com o Bigtable.

Para executar este programa de amostra, siga as instruções do exemplo no GitHub.

Como usar a biblioteca de cliente do Cloud com o Bigtable

O aplicativo de amostra conecta-se ao Bigtable e demonstra algumas operações simples.

Como solicitar a biblioteca de cliente

A amostra requer o módulo @google-cloud/bigtable, que fornece a classe Bigtable.

const {Bigtable} = require('@google-cloud/bigtable');

Como se conectar ao Bigtable

Para se conectar ao Bigtable, crie um novo objeto Bigtable. Em seguida, chame o método instance() para receber um objeto Instance que representa sua instância do Bigtable.

const bigtableClient = new Bigtable();
const instance = bigtableClient.instance(INSTANCE_ID);

Como criar uma tabela

Chame o método table() da instância para receber um objeto Table que represente a tabela para saudações "hello world". Se a tabela não existir, chame o método create() da tabela para criar uma tabela com um único grupo de colunas que mantenha uma versão de cada valor.

const table = instance.table(TABLE_ID);
const [tableExists] = await table.exists();
if (!tableExists) {
  console.log(`Creating table ${TABLE_ID}`);
  const options = {
    families: [
      {
        name: COLUMN_FAMILY_ID,
        rule: {
          versions: 1,
        },
      },
    ],
  };
  await table.create(options);
}

Como gravar linhas em uma tabela

Use uma matriz de strings de saudação para criar algumas linhas novas na tabela. Para isso, chame o método map() da matriz para criar uma nova matriz de objetos que representem linhas e, em seguida, chame o método insert() para adicionar as linhas à tabela.

console.log('Write some greetings to the table');
const greetings = ['Hello World!', 'Hello Bigtable!', 'Hello Node!'];
const rowsToInsert = greetings.map((greeting, index) => ({
  // Note: This example uses sequential numeric IDs for simplicity, but this
  // pattern can result in poor performance in a production application.
  // Rows are stored in sorted order by key, so sequential keys can result
  // in poor distribution of operations across nodes.
  //
  // For more information about how to design an effective schema for Cloud
  // Bigtable, see the documentation:
  // https://cloud.google.com/bigtable/docs/schema-design
  key: `greeting${index}`,
  data: {
    [COLUMN_FAMILY_ID]: {
      [COLUMN_QUALIFIER]: {
        // Setting the timestamp allows the client to perform retries. If
        // server-side time is used, retries may cause multiple cells to
        // be generated.
        timestamp: new Date(),
        value: greeting,
      },
    },
  },
}));
await table.insert(rowsToInsert);

Como criar um filtro

Antes de ler os dados que você gravou, crie um filtro para limitar os dados que o Bigtable retorna. Com esse filtro, o Bigtable retornará apenas a célula mais recente de cada coluna, mesmo que ela contenha células mais antigas.

const filter = [
  {
    column: {
      cellLimit: 1, // Only retrieve the most recent version of the cell.
    },
  },
];

Como ler uma linha pela chave dela

Chame o método row() da tabela para receber uma referência à linha com uma chave de linha específica. Em seguida, chame o método get() da linha, passando o filtro, para receber uma versão de cada valor nessa linha.

console.log('Reading a single row by row key');
const [singleRow] = await table.row('greeting0').get({filter});
console.log(`\tRead: ${getRowGreeting(singleRow)}`);

Como verificar todas as linhas da tabela

Chame o método getRows() da tabela, transmitindo o filtro, para receber todas as linhas na tabela. Como você transmitiu no filtro, o Bigtable retornará apenas uma versão de cada valor.

console.log('Reading the entire table');
// Note: For improved performance in production applications, call
// `Table#readStream` to get a stream of rows. See the API documentation:
// https://cloud.google.com/nodejs/docs/reference/bigtable/latest/Table#createReadStream
const [allRows] = await table.getRows({filter});
for (const row of allRows) {
  console.log(`\tRead: ${getRowGreeting(row)}`);
}

Como excluir tabelas

Exclua a tabela com o método delete().

console.log('Delete the table');
await table.delete();

Funcionamento em conjunto

Veja o exemplo de código completo sem comentários.



const {Bigtable} = require('@google-cloud/bigtable');

const TABLE_ID = 'Hello-Bigtable';
const COLUMN_FAMILY_ID = 'cf1';
const COLUMN_QUALIFIER = 'greeting';
const INSTANCE_ID = process.env.INSTANCE_ID;

if (!INSTANCE_ID) {
  throw new Error('Environment variables for INSTANCE_ID must be set!');
}

const getRowGreeting = row => {
  return row.data[COLUMN_FAMILY_ID][COLUMN_QUALIFIER][0].value;
};

(async () => {
  try {
    const bigtableClient = new Bigtable();
    const instance = bigtableClient.instance(INSTANCE_ID);

    const table = instance.table(TABLE_ID);
    const [tableExists] = await table.exists();
    if (!tableExists) {
      console.log(`Creating table ${TABLE_ID}`);
      const options = {
        families: [
          {
            name: COLUMN_FAMILY_ID,
            rule: {
              versions: 1,
            },
          },
        ],
      };
      await table.create(options);
    }

    console.log('Write some greetings to the table');
    const greetings = ['Hello World!', 'Hello Bigtable!', 'Hello Node!'];
    const rowsToInsert = greetings.map((greeting, index) => ({
      key: `greeting${index}`,
      data: {
        [COLUMN_FAMILY_ID]: {
          [COLUMN_QUALIFIER]: {
            timestamp: new Date(),
            value: greeting,
          },
        },
      },
    }));
    await table.insert(rowsToInsert);

    const filter = [
      {
        column: {
          cellLimit: 1, // Only retrieve the most recent version of the cell.
        },
      },
    ];

    console.log('Reading a single row by row key');
    const [singleRow] = await table.row('greeting0').get({filter});
    console.log(`\tRead: ${getRowGreeting(singleRow)}`);

    console.log('Reading the entire table');
    const [allRows] = await table.getRows({filter});
    for (const row of allRows) {
      console.log(`\tRead: ${getRowGreeting(row)}`);
    }

    console.log('Delete the table');
    await table.delete();
  } catch (error) {
    console.error('Something went wrong:', error);
  }
})();