Olá, mundo do Node.js

Este exemplo de código é uma aplicação "hello world" que é executada no Node.js. O exemplo ilustra como concluir as seguintes tarefas:

  • Configure a autenticação
  • Estabeleça ligação a uma instância do Bigtable.
  • Criar uma nova tabela.
  • Escreva dados na tabela.
  • Ler os dados novamente.
  • Eliminar a tabela.

Configure a autenticação

Para usar os Node.js exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

    Instale a CLI Google Cloud.

    Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

    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.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

Para mais informações, consulte Set up authentication for a local development environment.

Executar o exemplo

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

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

Usar a biblioteca cliente da Google Cloud com o Bigtable

A aplicação de exemplo liga-se ao Bigtable e demonstra algumas operações simples.

Requerer a biblioteca de cliente

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

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

Associar ao Bigtable

Para estabelecer ligação ao Bigtable, crie um novo objeto Bigtable. Em seguida, chame o método instance() para obter um objeto Instance que representa a sua instância do Bigtable.

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

Criar uma tabela

Chame o método table() da instância para obter um objeto Table que represente a tabela de saudações "Olá mundo". Se a tabela não existir, chame o método create() da tabela para criar uma tabela com uma única família de colunas que retenha uma versão de cada valor.

const {BigtableTableAdminClient} = require('@google-cloud/bigtable').v2;
const adminClient = new BigtableTableAdminClient();
const projectId = await adminClient.getProjectId();

let tableExists = true;
try {
  await adminClient.getTable({
    name: `projects/${projectId}/instances/${INSTANCE_ID}/tables/${TABLE_ID}`,
  });
} catch (e) {
  if (e.code === 5) {
    tableExists = false;
  }
}
if (!tableExists) {
  console.log(`Creating table ${TABLE_ID}`);
  const {BigtableTableAdminClient} = require('@google-cloud/bigtable').v2;
  const adminClient = new BigtableTableAdminClient();
  const projectId = await adminClient.getProjectId();
  await adminClient.createTable({
    parent: `projects/${projectId}/instances/${INSTANCE_ID}`,
    tableId: TABLE_ID,
    table: {
      columnFamilies: {
        [COLUMN_FAMILY_ID]: {
          gcRule: {
            maxNumVersions: 1,
          },
        },
      },
    },
  });
}

Escrever linhas numa tabela

Use uma matriz de strings de saudação para criar algumas novas linhas para a tabela: chame o método map() da matriz para criar uma nova matriz de objetos que representam linhas e, em seguida, chame o método insert() da tabela 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);

Criar um filtro

Antes de ler os dados que escreveu, crie um filtro para limitar os dados que o Bigtable devolve. Este filtro indica ao Bigtable que deve devolver apenas a célula mais recente de cada coluna, mesmo que a coluna contenha células mais antigas.

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

Ler uma linha pela respetiva chave de linha

Chame o método row() da tabela para obter uma referência à linha com uma chave de linha específica. Em seguida, chame o método get() da linha, transmitindo o filtro, para obter 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)}`);

Analisar todas as linhas da tabela

Chame o método getRows() da tabela, transmitindo o filtro, para obter todas as linhas na tabela. Como transmitiu o filtro, o Bigtable devolve 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)}`);
}

Eliminar uma tabela

Elimine a tabela com o método delete() da tabela.

console.log('Delete the table');
const request = {
  name: `projects/${projectId}/instances/${INSTANCE_ID}/tables/${TABLE_ID}`,
};
await adminClient.deleteTable(request);

A reunir tudo

Segue-se 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 {BigtableTableAdminClient} = require('@google-cloud/bigtable').v2;
    const adminClient = new BigtableTableAdminClient();
    const projectId = await adminClient.getProjectId();

    let tableExists = true;
    try {
      await adminClient.getTable({
        name: `projects/${projectId}/instances/${INSTANCE_ID}/tables/${TABLE_ID}`,
      });
    } catch (e) {
      if (e.code === 5) {
        tableExists = false;
      }
    }
    if (!tableExists) {
      console.log(`Creating table ${TABLE_ID}`);
      const {BigtableTableAdminClient} = require('@google-cloud/bigtable').v2;
      const adminClient = new BigtableTableAdminClient();
      const projectId = await adminClient.getProjectId();
      await adminClient.createTable({
        parent: `projects/${projectId}/instances/${INSTANCE_ID}`,
        tableId: TABLE_ID,
        table: {
          columnFamilies: {
            [COLUMN_FAMILY_ID]: {
              gcRule: {
                maxNumVersions: 1,
              },
            },
          },
        },
      });
    }

    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');
    const request = {
      name: `projects/${projectId}/instances/${INSTANCE_ID}/tables/${TABLE_ID}`,
    };
    await adminClient.deleteTable(request);
  } catch (error) {
    console.error('Something went wrong:', error);
  }
})();