Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Imports the Google Cloud client library
const { BigQuery } = require('@google-cloud/bigquery');
// Defines the location of the dataset and tables
const location = 'US';
// Creates a BigQuery client
const bigquery = new BigQuery({
// The relative file path to your Service Account key file
keyFilename: 'bigquery-sa.json',
// The GCP project ID we want to work in
projectId: 'YOUR_GCP_PROJECT_ID'
});
/**
* Create a new dataset and return its ID
* @param {string} datasetName
* @returns {Promise<string>}
*/
const createDataset = async (datasetName) => {
const [dataset] = await bigquery.createDataset(datasetName, location);
console.log(`Dataset '${dataset.id}' created.`);
return dataset.id;
}
/**
* Create a new table and return its ID
* @param {string} datasetId The ID of the parent dataset
* @param {string} tableName The name of the table that should be created
* @returns {Promise<string>}
*/
const createTable = async (datasetId, tableName) => {
// Define Schema of BigQuery Table
const schema = [
{ name: 'Name', type: 'STRING', mode: 'REQUIRED' },
{ name: 'Age', type: 'INTEGER' },
{ name: 'Weight', type: 'FLOAT' },
{ name: 'IsMagic', type: 'BOOLEAN', description: "Is this magic?" },
];
const options = {
location, schema
}
// Create a new BigQuery table in the dataset
const [table] = await bigquery
.dataset(datasetId)
.createTable(tableName, options);
console.log(`Table '${table.id}' created.`);
return table.id;
}
/**
* Bundle above methods togeter and run them
*/
const main = async () => {
const datasetId = await createDataset('my_test_dataset');
await createTable(datasetId, 'my_test_table');
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment