GAS: BigQuery Загрузить в существующую таблицу
У меня более 350000 журналов вызовов RingCentral, которые я хочу загрузить в BigQuery, чтобы я мог использовать запросы SQL для извлечения и анализа отчетов. В настоящее время они хранятся в виде 23 файлов.csv, каждый из которых не превышает 10 МБ, установленный API-интерфейсом BigQuery. Я хочу использовать Google Apps Script для загрузки данных CSV, чтобы все 350 тыс. Записей находились в одной таблице. Вот код, который у меня есть:
function uploadCSVtoBigQuery() {
try {
var CSVFolder = "Drive ID to Folder A";
var ProcessedFolder = "Drive ID to Folder B";
var projectId = 'ring-central-call-logs';
var datasetId = 'RingCentral';
var tableId = 'Calls';
//CSVFolder = getDriveFolder(CSVFolder);
var CSVFolder = DriveApp.getFolderById(CSVFolder);
//ProcessedFolder = getDriveFolder(ProcessedFolder);
var ProcessedFolder = DriveApp.getFolderById(ProcessedFolder);
if (CSVFolder && ProcessedFolder) {
Logger.log("Folders Appear Valid");
var data, job, file, files = CSVFolder.getFiles();
while (files.hasNext()) {
file = files.next();
if (file.getMimeType() === "text/csv") {
data = file.getBlob().setContentType('application/octet-stream');
job = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1
}
}
};
job = BigQuery.Jobs.insert(job, projectId, data);
file.makeCopy(file.getName(), ProcessedFolder);
file.setTrashed(true);
Logger.log('Job status for %s https://bigquery.cloud.google.com/jobs/%s', file.getName(), projectId);
} else{Logger.log(file.getMimeType()+" Is not a valid file type.");}
}
} else{Logger.log('One of your folders is not valid');}
Logger.log('Finished');
} catch(e) {
Logger.log(e.toString());
}
}
// Return the ID of the Google Drive nested folder
function getDriveFolder(name) {
var results, folders = name.split("\\");
var folder = DriveApp.getRootFolder();
for (var i=0; i<folders.length; i++) {
if (folders[i] === "") continue;
results = folder.getFoldersByName(folders[i]);
if (results.hasNext()) {
folder = results.next();
} else {
folder = folder.createFolder(folders[i]);
}
}
return folder;
}
При запуске функции я получаю ответ JSON следующим образом:
GoogleJsonResponseException: Using table ring-central-call-logs:RingCentral.Calls is not allowed for this operation because of its type. Try using a different table that is of type TABLE.
Чтобы проверить свой мозг, я попытался запустить REST API в API Explorer, например так:
POST https://www.googleapis.com/bigquery/v2/projects/ring-central-call-logs/datasets/RingCentral/tables/Calls/insertAll?key={YOUR_API_KEY}
{
"skipInvalidRows": true,
"rows": [
{
"json": {
"User": "Nathaniel",
"CallStartTime": "2018-07-09 15:45:10",
"From": "123456789",
"To": "9876543211",
"DurationSeconds": "15",
"CallDirection": "out",
"CallResult": "Failed",
"QueueName": "Test Queue"
}
}
],
"kind": "bigquery#tableDataInsertAllRequest"
}
И получил эту похожую ошибку:
400
- Show headers -
{
"error": {
"code": 400,
"message": "Cannot add rows to a table of type EXTERNAL.",
"errors": [
{
"message": "Cannot add rows to a table of type EXTERNAL.",
"domain": "global",
"reason": "invalid"
}
],
"status": "INVALID_ARGUMENT"
}
}
Снимок экрана здесь для схемы выглядит так, как я ввожу: Я мог бы предположить, что у меня возникли проблемы с разрешениями при чтении, но я вполне могу запустить функцию Query в GAS. Могу ли я получить помощь, чтобы выяснить, почему это не работает? Спасибо!