Я хотел вставить тысячи записей в базу данных с помощью команды INSERT в php-скрипте, так как к ней будет проще получить доступ, но https://developers.google.com/bigquery/docs/query-reference, это не показывает команду INSERT, которую можно использовать при запросе в php, например, $quert->setQuery ("Вставить в... значения..."). Пробовали это в таблице запросов веб-консоли BigQuery, но, похоже, это не работает. Можно ли использовать setQuery() с какой-либо другой командой, чтобы вставить данные ?
INSERT в части запроса BigQuery, используя google-api-php-client
Ответы (2)
BigQuery не поддерживает команду INSERT. Вам нужно будет создать задание загрузки. См. https://developers.google.com/bigquery/docs/import#localimport для получения дополнительной информации.
В дополнение к ответу Джордана, вот фрагмент кода, который поможет вам начать использовать Google BigQuery API и клиентская библиотека Google API PHP для загрузки собственных данных в BigQuery программным путем. Обратите внимание, что этот фрагмент просто выдает необработанный ответ API задания загрузки, включая идентификатор задания на экран — вам нужно будет добавить собственную логику опроса, чтобы проверить статус задания загрузки.
(В ближайшее время мы добавим дополнительную документацию по загрузке ваших собственных данных, а также дополнительные примеры PHP).
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_BigqueryService.php";
session_start();
$client = new Google_Client();
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setScopes(array('https://www.googleapis.com/auth/bigquery'));
$client->setClientId('XXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXX');
$client->setRedirectUri('http://YOURAPPLICATION/index.php');
// Instantiate a new BigQuery Client
$bigqueryService = new Google_BigqueryService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
?>
<!doctype html>
<html>
<head>
<title>BigQuery API Sample</title>
</head>
<body>
<div id='container'>
<div id='top'><h1>BigQuery API Sample</h1></div>
<div id='main'>
<?php
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
// Your project number, from the developers.google.com/console project you created
// when signing up for BigQuery
$project_number = 'XXXXXXXXXXXXXX';
// Information about the destination table
$destination_table = new Google_TableReference();
$destination_table->setProjectId($project_number);
$destination_table->setDatasetId('php_test');
$destination_table->setTableId('my_new_table');
// Information about the schema for your new table
$schema_fields = array();
$schema_fields[0] = new Google_TableFieldSchema();
$schema_fields[0]->setName('first');
$schema_fields[0]->setType('string');
$schema_fields[1] = new Google_TableFieldSchema();
$schema_fields[1]->setName('last');
$schema_fields[1]->setType('string');
$destination_table_schema = new Google_TableSchema();
$destination_table_schema->setFields($schema_fields);
// Set the load configuration, including source file(s) and schema
$load_configuration = new Google_JobConfigurationLoad();
$load_configuration->setSourceUris(array('gs://YOUR_GOOGLE_CLOUD_STORAGE_BUCKET/file.csv'));
$load_configuration->setDestinationTable($destination_table);
$load_configuration->setSchema($destination_table_schema);
$job_configuration = new Google_JobConfiguration();
$job_configuration->setLoad($load_configuration);
$load_job = new Google_Job();
$load_job->setKind('load');
$load_job->setConfiguration($job_configuration);
$jobs = $bigqueryService->jobs;
$response = $jobs->insert($project_number, $load_job);
echo '<pre>';
print_r($response);
echo '</pre>';
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Authorize Access to the BigQuery API</a>";
}
?>
</div>
</div>
</body>
</html>