3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaでBigQueryのテーブルの存在を確認する

Posted at

はじめに

JavaでBigQueryのテーブルがあるかないか確認する方法です。

GCPまわりはAPIのSDK(com.google.api.services.*)よりもそれをラップしたSDK(com.google.cloud.*)を使う方がだいぶ簡単ですね。
ぐぐるとcom.google.api.servicesのほうがよく出るのでそれを真似るととても複雑なコードになってしまいます :sweat_smile:

依存

build.gradleはこんな感じです。

apply plugin: 'java'
apply plugin: 'application'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.cloud:google-cloud-bigquery:+'
}

mainClassName = "Main"

run {
    if (project.hasProperty('args')) {
        args project.args.split('\\s+')
    }
}

コード

見つかればFound、見つからなければNot foundと出力します。
引数でサービスアカウントのJSON Keyを指定すればそれで認証し、なければデフォルトのアカウントを使うようになっています。

import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.*;

import java.io.FileInputStream;
import java.io.IOException;

public class Main {
    private static final String DATASET = "yourdataset";
    private static final String TABLE = "yourtable";

    public static void main(String args[]) throws IOException {
        BigQuery bigQuery;
        if (args.length > 0) {
            bigQuery = getClientWithJsonKey(args[0]);
        } else {
            bigQuery = BigQueryOptions.getDefaultInstance().getService();
        }

        Table table = bigQuery.getTable(DATASET, TABLE);
        if (table != null) {
            System.out.println("Found!");
        } else {
            System.err.println("Not found");
        }
    }

    private static BigQuery getClientWithJsonKey(String key) throws IOException {
        return BigQueryOptions.newBuilder()
                .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(key)))
                .build()
                .getService();
    }
}

実行

$ ./gradlew run -Pargs="/path/to/key.json"

# もしくは
$ ./gradlew run

おわりに

com.google.api.servicesの方だけで頑張るとこんな感じで、認証まわりだけでもめちゃくちゃ複雑です :tired_face:
https://github.com/googlearchive/bigquery-samples-java/blob/master/src/main/java/com/google/cloud/bigquery/samples/BigQueryJavaGettingStarted.java

今回のコードはこちらにあります :pencil:
https://github.com/nownabe/examples/tree/master/bigquery-table-existence

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?