3
5

More than 3 years have passed since last update.

node.jsからBigQueryを使う

Last updated at Posted at 2019-11-17

久しぶりに触ったらハマった(ハマる要素はありませんが)のでメモ。

前提

  • BigQuery側でデータセットおよびテーブルが作成されている。
  • 適切なサービスアカウントが作成され、認証用のjsonが(カレントに)ダウンロードされている。

準備

mkdir bq-test
cd bq-test
npm init -f
npm install --save @google-cloud/bigquery
touch index.js

実装

index.jsを実装します。下記のような感じ。

index.js
const { BigQuery } = require('@google-cloud/bigquery');

const bigquery = new BigQuery({
    projectId: 'your-project-id',
    keyFilename: 'path/to/key.json'
});

const query = "select * from test.members";

//simple
bigquery.query(query)
    .then(data => {
        const rows = data[0];
        rows.forEach(row => {
            console.log(JSON.stringify(row));
        })
    })
    .catch(error => {
        console.log(error);
    });

//with options
const options = {
    query: query,
    useLegacySql: false,
}

bigquery.createQueryJob(options)
    .then(results => {
        const [job] = results;
        return job.getQueryResults();
    })
    .then(results => {
        const [rows] = results;
        rows.forEach(row => {
            console.log(JSON.stringify(row));
        })
    })
    .catch(error => {
        console.log(error);
    })

実行

あくまで参考ですが(同じ結果が2回出ます)。

node index.js

{"id":1,"name":"hoge","age":22}
{"id":2,"name":"foo","age":33}
{"id":3,"name":"boo","age":44}
{"id":1,"name":"hoge","age":22}
{"id":2,"name":"foo","age":33}
{"id":3,"name":"boo","age":44}

参考

3
5
0

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
3
5