Last active
May 14, 2022 22:16
-
-
Save mr-pascal/b1d85a4ca7b72710b982a91404d92e00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
Hi Team,
I want to truncate the table in Bigquery, but I'm unable to achieve it.
Could you please help me with this?
Below is the code that I have used:
// Imports the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
// Defines the location of the dataset and tables
// Creates a BigQuery client
const truncate = async () => {
const bigquery = new BigQuery({
keyFilename: 'bigquery-sa.json',
projectId: 'ioqa-342912',
});
const sqlQuery =
truncate table \
ioqa-342912.1234.Try``;const options = {
query: sqlQuery,
location: 'US',
};
const [rows] = bigquery.query(options);
console.log(rows);
};
const main = async () => {
await truncate();
};
main();