הוספת שורות לזרם כתיבה (גרסה 1)

הוספת שורות שעברו סריאליזציה לטבלה ב-BigQuery באמצעות זרם כתיבה.

דוגמת קוד

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Node.js API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

'use strict';

const {BigQueryWriteClient, adapt} = require('@google-cloud/bigquery-storage');
const {status} = require('@grpc/grpc-js');
const protobuf = require('protobufjs');

const client = new BigQueryWriteClient();

/**
 * Use the appendRows method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id').
 * @param {string} datasetId - The BigQuery dataset ID (for example, 'example_dataset').
 * @param {string} tableId - The BigQuery table ID (for example, 'example_table').
 * @param {string} streamId - ID of the write stream (server-generated stream ID from CreateWriteStream, or '_default' for the table's default stream).
 */
async function appendRows(projectId, datasetId, tableId, streamId) {
  try {
    const writeStream = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}/streams/${streamId}`;

    // Define the schema for the serialized rows
    const root = protobuf.Root.fromJSON({
      nested: {
        CustomerRecord: {
          fields: {
            customerName: {
              type: 'string',
              id: 1,
            },
            rowNum: {
              type: 'int64',
              id: 2,
            },
          },
        },
      },
    });

    const CustomerRecord = root.lookupType('CustomerRecord');
    const descriptor = CustomerRecord.toDescriptor('proto2');
    const protoDescriptor = adapt.normalizeDescriptor(descriptor);

    // Serialize sample rows matching the schema
    const row = {
      customerName: 'example-customer',
      rowNum: 1,
    };
    const serializedRow = CustomerRecord.encode(row).finish();

    // Construct the append rows request with schema and rows
    const request = {
      writeStream,
      protoRows: {
        writerSchema: {
          protoDescriptor,
        },
        rows: {
          serializedRows: [serializedRow],
        },
      },
    };

    // Open bidirectional stream and register handlers
    const stream = client.appendRows();

    const appendPromise = new Promise((resolve, reject) => {
      stream.on('data', response => {
        if (response.error) {
          reject(new Error(response.error.message));
          return;
        }
        resolve(response);
      });
      stream.on('error', reject);
    });

    stream.write(request);
    stream.end();

    const response = await appendPromise;
    console.log(`Successfully appended rows to: ${writeStream}`);
    if (response.appendResult && response.appendResult.offset) {
      console.log(`Append result offset: ${response.appendResult.offset}`);
    }
  } catch (err) {
    if (err.code !== undefined && Object.values(status).includes(err.code)) {
      console.error(`BigQuery Storage API error (code ${err.code}):`, err.message);
    } else {
      throw err;
    }
  }
}

module.exports = { appendRows };

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , ראו דפדפן לדוגמה שלGoogle Cloud .