Skip to content
Snippets Groups Projects
LoadJson.java 2.71 KiB
Newer Older
Mads Greni Arnesen's avatar
Mads Greni Arnesen committed
package com.application.DataBase;

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.FormatOptions;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.LoadJobConfiguration;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.TableId;

import java.io.File;

// Sample to load JSON data from Cloud Storage into a new BigQuery table
public class LoadJson {

    public static void runLoadJsonFromGCS() {
        // TODO(developer): Replace these variables before running the sample.
        String datasetName = "124";
        String tableName = "int_sd_winccsensordata";
        String credentialsPath = (".\\src\\main\\resources\\com.application\\sf-drying-optimization-1e234ad2b0f4.json");
        Schema schema =
                Schema.of(
                        Field.of("VariantValue", StandardSQLTypeName.INT64),
                        Field.of("TimeStamp", StandardSQLTypeName.INT64));
        loadJsonFromGCS(datasetName, tableName, credentialsPath, schema);
    }

    public static void loadJsonFromGCS(
            String datasetName, String tableName, String sourceUri, Schema schema) {
        try {
            // Initialize client that will be used to send requests. This client only needs to be created
            // once, and can be reused for multiple requests.
            BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

            TableId tableId = TableId.of(datasetName, tableName);
            LoadJobConfiguration loadConfig =
                    LoadJobConfiguration.newBuilder(tableId, sourceUri)
                            .setFormatOptions(FormatOptions.json())
                            .setSchema(schema)
                            .build();

            // Load data from a GCS JSON file into the table
            Job job = bigquery.create(JobInfo.of(loadConfig));
            // Blocks until this load table job completes its execution, either failing or succeeding.
            job = job.waitFor();
            if (job.isDone()) {
                System.out.println("Json from GCS successfully loaded in a table");
            } else {
                System.out.println(
                        "BigQuery was unable to load into the table due to an error:"
                                + job.getStatus().getError());
            }
        } catch (BigQueryException | InterruptedException e) {
            System.out.println("Column not added during load append \n" + e.toString());
        }
    }
}