【问题标题】:Bigquery + PHP examplesBigquery + PHP 示例
【发布时间】:2012-09-06 23:32:45
【问题描述】:

谁能提供将 Bigquery API 与 PHP 结合使用的工作示例。我看到有 python 和 java 的示例,但找不到任何 PHP 的示例。

这里是大查询浏览器https://bigquery.cloud.google.com/?pli=1

例如,您可以在浏览器中运行此 SQL

SELECT corpus,count(*) FROM publicdata:samples.shakespeare 
group by corpus limit 5;

我想通过 PHP 模拟类似的调用。

即使是关于如何使用 PHP API 的粗略示例也会有很大帮助。

【问题讨论】:

  • 如果你安装了 CLI 客户端,你可以直接执行它:) exec('bq query " SELECT corpus,count(*) FROM publicdata:samples.shakespeare group by corpus limit 5;')
  • @Frank,我不想要 CLI 客户端。想与PHP集成

标签: php google-bigquery


【解决方案1】:

使用适用于 PHP 的 Google API 客户端。这是一个执行单个同步查询作业的脚本的简单示例。这使用在可下载的 API 客户端中找到的类名。注意:从 SVN 提取的源具有不同的类名。请注意您必须在哪里为客户端密码、客户端 ID、重定向 URI 和项目 ID 添加自己的值。

<?php

require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiBigqueryService.php';

session_start();

$client = new apiClient();
// Visit https://developers.google.com/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.

$client->setClientId('XXXXXXXXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('http://www_your_domain.com/somescript.php');

// Your project id
$project_id = 'XXXXXXXXXXXXXXXXXXXX';

// Instantiate a new BigQuery Client 
$bigqueryService = new apiBigqueryService($client);

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_SESSION['access_token'])) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $client->setAccessToken($client->authenticate());
  $_SESSION['access_token'] = $client->getAccessToken();
}

if (isset($_GET['code'])) {
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
?>
<!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
  $query = new QueryRequest();
  $query->setQuery('SELECT TOP( title, 10) as title, COUNT(*) as revision_count FROM [publicdata:samples.wikipedia] WHERE wp_namespace = 0;');

  $jobs = $bigqueryService->jobs;
  $response = $jobs->query($project_id, $query);

  // Do something with the BigQuery API $response data
  print_r($response);

?>
  </div>
</div>
</body>
</html>

【讨论】:

  • 顺便说一句,显然“$response”是一个多维数组。上面的示例只是将原始响应吐到屏幕上,但您可以根据需要对其进行解析。
【解决方案2】:

以前的答案有过时的代码。以下示例应该适用于更新的 API (https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php):

require_once '../source/application/libraries/Google/autoload.php';

public function createGClient(){
  define("CLIENT_ID", "{PROJECT_ID}.apps.googleusercontent.com");
  define("SERVICE_ACCOUNT_NAME","{SERVICE_ACCOUNT EMAIL FROM CONSOLE}");
  define("KEY_FILE",'../{FILENAME}.p12');

  define("PROJECT_ID","{PROJECT_ID}");
  define("DATASET_ID","{DATASET_ID}");
  define("TABLE_ID","");

  $this->client = new Google_Client();
  $this->client->setApplicationName("{NAME}");

  $key = file_get_contents(KEY_FILE);
  $this->client->setAssertionCredentials(new Google_Auth_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/bigquery'), $key, "notasecret"));
  $this->client->setClientId(CLIENT_ID);

  $this->service = new Google_Service_Bigquery($this->client);
}

public function runQuery(){
  // To see the a list of tables  
  print_r($this->service->tables->listTables(PROJECT_ID, DATASET_ID));

  // To see details of a table
  print_r($this->service->tables->get(PROJECT_ID, DATASET_ID, TABLE_ID));

  // To query a table
  $jobs = $this->service->jobs;
  $query = new Google_Service_Bigquery_QueryRequest();
  $query->setQuery("SELECT * FROM wherever;");
  $response = $jobs->query(PROJECT_ID, $query);
  print_r($response);
}

这是针对服务帐户的http://michaelheap.com/using-the-php-sdk-with-google-bigquery/ 中给出的示例的修改版本。要使用客户帐户,您需要使用 oauth2 并有一个 pingback 地址。

【讨论】:

  • 你就是那个男人,我尝试了几种不同的方法,但最终还是找到了。为什么谷歌在 PHP 上如此落后?
【解决方案3】:

我在查找示例时遇到了很多问题。 这是一个基本的异步查询,但可以演示当前 PHP API 的使用,您可以在此处查看用于异步查询的 API 的 Python/Java 示例:https://developers.google.com/bigquery/querying-data

请注意,我不是在参考如何设置 $client 凭据,因为它在其他地方都有很好的记录。

    $bq = new Google_BigqueryService($client);

    //build query
    $sql = 'select * from example.table LIMIT 10';

    $job = new Google_Job();
    $config = new Google_JobConfiguration();
    $queryConfig = new Google_JobConfigurationQuery();
    $config->setQuery($queryConfig);

    $job->setConfiguration($config);
    $queryConfig->setQuery($sql);

    $insert = new Google_Job($bq->jobs->insert(PROJECT_ID,$job));
    $jr = $insert->getJobReference();
    $jobId = $jr['jobId'];

    $res = new Google_GetQueryResultsResponse($bq->jobs->getQueryResults(PROJECT_ID, $jobId));

//see the results made it as an object ok:
        var_dump($results);

【讨论】:

  • 这会将查询保存到临时表吗?
【解决方案4】:
/**
 * Executes and returns bigQuery response with 'INTERACTIVE' priority
 * $this->service is the object of Google_Service_Bigquery
 *          $this->service = new Google_Service_Bigquery($this->client);
 * @param String $sql
 * @return Google_Service_Bigquery_GetQueryResultsResponse
 */
public function execute($sql) {
    $job = new Google_Service_Bigquery_Job();
    $config = new Google_Service_Bigquery_JobConfiguration();
    $queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
    $queryConfig->setQuery($sql);
    /**
     * Priority is set to INTERACTIVE for faster response options are 'BATCH'/'INTERACTIVE' 
     */
    $queryConfig->setPriority("INTERACTIVE");
    $config->setQuery($queryConfig);
    $job->setId(md5("$sql_{microtime()}"));
    $job->setConfiguration($config);

    $running = $this->service->jobs->insert('divine-builder-586', $job);
    /* @var $running Google_Service_Bigquery_Job */
    $jr = $running->getJobReference();
    $jobId = $jr['jobId'];
    $res = $this->service->jobs->getQueryResults('divine-builder-586', $jobId);
    /* @var $res Google_Service_Bigquery_GetQueryResultsResponse */
    return $res;
}

【讨论】:

  • 不工作,即使在给客户令牌后,得到错误“需要登录”
猜你喜欢
  • 1970-01-01
  • 2019-05-02
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多