Далее, мы хотели бы сохранить почасовую сводку продаж, созданную в предыдущем посте в BigQuery.
Клиентская библиотека BigQuery Node.js
Играя с данными о продажах и приборной панелью, мне часто нужно обновить или изменить схему базы данных, чтобы добавить различные аналитические представления. Было бы намного проще управлять BigQuery из клиента Node.js, чем работать вручную на странице администратора. Клиентский сценарий может использоваться как автоматизированный сценарий, а также для периодического обновления данных.
Есть хорошее руководство по установке для настройки клиента Node BigQuery. Библиотека Commander.js также полезна для разработки собственных инструментов командной строки BigQuery.
Создание и удаление таблицы из клиента Node
Вот пример создания и удаления таблицы из клиента BigQuery Node.js. Сохраните его как «/src/bigquery.js».
const BigQuery = require('@google-cloud/bigquery'); | |
const bigquery = new BigQuery({ YOUR_PROJECT_ID }); | |
const handleError = (err) => { | |
if (err && err.name === 'PartialFailureError') { | |
if (err.errors && err.errors.length > 0) { | |
console.log('Insert errors:'); | |
err.errors.forEach(error => console.error(error)); | |
} | |
} else { | |
console.error('ERROR:', err); | |
} | |
}; | |
module.exports = { | |
createTable: ({ datasetId, tableId, schema, partitionBy, isTest }) => { | |
const options = { schema }; | |
if (partitionBy) { | |
options.timePartitioning = { | |
field: partitionBy | |
}; | |
} | |
return new Promise((resolve, reject) => { | |
resolve(); | |
bigquery | |
.dataset(dataset) | |
.createTable(tableId, options) | |
.then(results => resolve(results[0])) | |
.catch(err => { | |
handleError(err); | |
reject(err); | |
}); | |
}); | |
}, | |
deleteTable: ({ datasetId, tableId, isTest }) => { | |
return new Promise((resolve, reject) => { | |
bigquery.dataset(dataset).table(tableId).exists() | |
.then( | |
exists => { | |
if (exists[0]) { | |
bigquery.dataset(dataset).table(tableId).delete() | |
.then(result => resolve(result)); | |
} else { | |
resolve('The table does not exists'); | |
} | |
} | |
) | |
.catch(err => { | |
handleError(err); | |
reject(err); | |
}); | |
}); | |
} | |
}; |
Определите схему для почасовой сводки продаж
Сохраните следующую схему как «/schemas/SchemaSalesByHour.js».
exports.SchemaSalesByHour = [ | |
{ | |
description: 'Date and hour of the transactions', | |
name: 'date_hour', | |
type: 'DATETIME', | |
mode: 'REQUIRED' | |
}, | |
{ | |
description: 'UTC timestamp of the transactions', | |
name: 'timestamp', | |
type: 'TIMESTAMP', | |
}, | |
{ | |
description: 'Day of the transactions', | |
name: 'day', | |
type: 'STRING', | |
mode: 'REQUIRED' | |
}, | |
{ | |
description: 'Day of the transactions by numeric, 1=Mon...6=Sat, 0=Sun', | |
name: 'day_num', | |
type: 'INT64', | |
mode: 'REQUIRED' | |
}, | |
{ | |
description: 'Hour of the transactions', | |
name: 'hour', | |
type: 'STRING', | |
mode: 'REQUIRED' | |
}, | |
{ | |
description: 'Name of the shop', | |
name: 'shop_name', | |
type: 'STRING', | |
mode: 'REQUIRED' | |
}, | |
{ | |
description: 'Number of transactions', | |
name: 'transactions', | |
type: 'INT64', | |
mode: 'NULLABLE' | |
}, | |
{ | |
description: 'Number of customers', | |
name: 'customers', | |
type: 'INT64', | |
mode: 'NULLABLE' | |
}, | |
{ | |
description: 'Total amount which customers paid, including VAT and service charges', | |
name: 'sales', | |
type: 'FLOAT64', | |
mode: 'NULLABLE' | |
}, | |
{ | |
description: 'VAT Tax', | |
name: 'tax', | |
type: 'FLOAT64', | |
mode: 'NULLABLE' | |
}, | |
{ | |
description: 'Cost', | |
name: 'cost', | |
type: 'FLOAT64', | |
mode: 'NULLABLE' | |
}, | |
{ | |
description: 'Amout of discount to be adjusted', | |
name: 'discount', | |
type: 'FLOAT64', | |
mode: 'NULLABLE' | |
}, | |
{ | |
description: 'Net = Total - Tax, used by the daily sales report.', | |
name: 'net', | |
type: 'FLOAT64', | |
mode: 'NULLABLE' | |
} | |
]; |
Команда для создания новой таблицы
Затем создайте следующий командный сценарий, чтобы потребовать файлы библиотеки и схемы, сохраните его как «./command/create.js».
const program = require('commander'); | |
const { createTable } = require('../src/bigquery'); | |
const { SchemaSalesByHour } = require('../schemas/SchemaSalesByHour'); | |
program | |
.version('0.1.0') | |
.option('-t, --table [table]', 'Specify the table to create', '') | |
.parse(process.argv); | |
if (program.table) { | |
console.log(`Create a new table ${program.table}`); | |
switch (program.table) { | |
case 'shop_sales_by_hour': | |
createTable({ | |
datasetId: 'stats', | |
tableId: program.table, | |
schema: SchemaSalesByHour, | |
isTest: false, | |
}).then(() => console.log(`${program.table} created.`)); | |
break; | |
default: | |
console.log(`Cannot find the database ${program.table}`); | |
} | |
} else { | |
console.log('Please specifiy the table to create by "-t TABLE_NAME"'); | |
} |
Чтобы создать таблицу, введите в терминале следующую команду.
% node ./commands/create.js -t shop_sales_by_hour
Команда сбросить стол
Сохраните команду как «./command/drop.js».
const program = require('commander'); | |
const { deleteTable } = require('../src/bigquery'); | |
program | |
.version('0.1.0') | |
.option('-t, --table [table]', 'Specify the table to drop', '') | |
.option('-d, --dataset [datasetId]', 'Specify the dataset of the table to drop.', '') | |
.parse(process.argv); | |
if (program.table) { | |
console.log(`Drop table: ${program.table}`); | |
const datasetId = program.dataset ? program.dataset : 'stats'; | |
deleteTable({ | |
datasetId, | |
tableId: program.table | |
}).then(() => console.log(`${program.table} dropped.`)); | |
} else { | |
console.log('Please specifiy the table to create by "-t TABLE_NAME"'); | |
} |
Чтобы удалить таблицу, введите в терминале следующую команду.
% node ./commands/drop.js -t shop_sales_by_hour