Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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());
}
}
}