LoginSignup
35

More than 5 years have passed since last update.

PHPでGoogle BigQueryにデータを登録する

Last updated at Posted at 2014-11-01

はじめに

BigQueryとは?

Googleのサービスの1つ。ビッグデータをGoogleの力で処理できる。

BigQueryのメリット

  • 文章内のテキスト検索も気軽にできるため、とりあえずデータ登録してあとで検索・分析することを考えた。

BigQueryのデメリット

  • 有料。とは言っても、自分でMySQLなどのDBサーバを構築してチューニングして~という手間と管理が省ける分 お値段以上の魅力を感じる。
  • 遅い RDBで主キーがわかっている状態の検索に比べて遅く感じる。1レコードしか登録がない状態でも検索に最低3秒くらいかかる。
  • 重複レコードが発生する 主キーの設定ができないため、普通にInsertすると重複するレコードが登録できてしまう。

PHPでGoogle BigQueryにデータを登録する

前準備

  • Google BigQuery API client librariesから、Google APIs Client Library for PHP (beta)をダウンロードしてセットアップ。
  • Google Developers Consoleから認証情報にて、OAuthを登録・作成する。

BigQueryのクライアントを作る。

1st
    require_once './Google/Client.php';
    require_once './Google/Service/Bigquery.php';

    define('CLIENT_ID', 'xxxx-xxxx.apps.googleusercontent.com');
    define('SERVICE_ACCOUNT_NAME', 'xxxx-xxxx@developer.gserviceaccount.com');
    define('KEY_FILE', './xxxx.p12');

    $client = new Google_Client();
    $client->setApplicationName('Insert BigQuery from php');

    $key = file_get_contents(KEY_FILE);

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

    $service = new Google_Service_Bigquery($client);

BigQueryへデータ登録

2nd

    define('PROJECT_ID', 'project-name');
    define('DATASET_ID', 'dataset-name');
    define('TABLE_ID', 'table-name');

    $data = array( 'a' => '1', 'b' => '2' );

    try {
        $rows = array();
        $row = new Google_Service_Bigquery_TableDataInsertAllRequestRows();
        $row->setJson( $data );  // $dataはjson_encodeしないで配列のまま
        $row->setInsertId( date('YmdHis') );
        $rows[0] = $row;

        $request = new Google_Service_Bigquery_TableDataInsertAllRequest();
        $request->setKind('bigquery#tableDataInsertAllRequest');
        $request->setRows($rows);

        $this->gbqService->tabledata->insertAll(PROJECT_ID, DATASET_ID , TABLE_ID, $request);
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

$row->setInsertId( date('YmdHis') ); の部分が主キー相当となるため、重複するレコードを作りたくない場合、主キーとして連結した文字列に設定する。今回date('YmdHis')を指定しているので、重複を気にせずガンガン登録している。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35