LoginSignup
11
8

More than 5 years have passed since last update.

Go言語でBigQueryのクエリを実行してみる

Posted at

概要

Go言語からBigQueryのクエリを実行してみたので、そのメモ。

import

Google提供のBigQueryのライブラリと、認証周りで使うライブラリをimport。

"google.golang.org/api/bigquery/v2"
"golang.org/x/net/context"
"golang.org/x/oauth2/jwt"

接続

GCPプロジェクトの権限を持つアカウント名と秘密鍵を使ってアクセスします。

cfg := jwt.Config{
    Email:      account,
    PrivateKey: pem,
    Scopes:     []string{bigquery.BigqueryScope},
    TokenURL:   "https://accounts.google.com/o/oauth2/token",
}
ctx := context.Background()
client := cfg.Client(ctx)
conn, err := bigquery.New(client)

クエリ

プロジェクトIDとクエリを指定して、実行する。

result, err := conn.Jobs.Query(projectId, &bigquery.QueryRequest{
    Query: "SELECT * FROM ....",
}).Do()

なおデータセットIDはクエリ内のテーブル名に含まれる。

結果

Rowsに結果が入っている。

for _, row := range result.Rows {
    for _, cell := range row.F {
        fmt.Print(cell.V)
        fmt.Print(",")
    }
    fmt.Print("\n")
}
11
8
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
11
8