Skip to content
This repository was archived by the owner on Mar 23, 2026. It is now read-only.

Commit 9044050

Browse files
author
Praful Makani
authored
docs(samples): add query external sheet temp table (#659)
1 parent 4b296a2 commit 9044050

File tree

2 files changed

+160
-0
lines changed

2 files changed

+160
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.bigquery;
18+
19+
// [START bigquery_query_external_sheets_temp]
20+
import com.google.auth.oauth2.GoogleCredentials;
21+
import com.google.auth.oauth2.ServiceAccountCredentials;
22+
import com.google.cloud.bigquery.BigQuery;
23+
import com.google.cloud.bigquery.BigQueryException;
24+
import com.google.cloud.bigquery.BigQueryOptions;
25+
import com.google.cloud.bigquery.ExternalTableDefinition;
26+
import com.google.cloud.bigquery.Field;
27+
import com.google.cloud.bigquery.GoogleSheetsOptions;
28+
import com.google.cloud.bigquery.QueryJobConfiguration;
29+
import com.google.cloud.bigquery.Schema;
30+
import com.google.cloud.bigquery.StandardSQLTypeName;
31+
import com.google.cloud.bigquery.TableResult;
32+
import com.google.common.collect.ImmutableSet;
33+
import java.io.IOException;
34+
35+
// Sample to queries an external data source using a temporary table
36+
public class QueryExternalSheetsTemp {
37+
38+
public static void runQueryExternalSheetsTemp() {
39+
// TODO(developer): Replace these variables before running the sample.
40+
String tableName = "MY_TABLE_NAME";
41+
String sourceUri =
42+
"https://docs.google.com/spreadsheets/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing";
43+
Schema schema =
44+
Schema.of(
45+
Field.of("name", StandardSQLTypeName.STRING),
46+
Field.of("post_abbr", StandardSQLTypeName.STRING));
47+
String query = String.format("SELECT * FROM %s WHERE name LIKE 'W%%'", tableName);
48+
queryExternalSheetsTemp(tableName, sourceUri, schema, query);
49+
}
50+
51+
public static void queryExternalSheetsTemp(
52+
String tableName, String sourceUri, Schema schema, String query) {
53+
try {
54+
55+
// Create credentials with Drive & BigQuery API scopes.
56+
// Both APIs must be enabled for your project before running this code.
57+
GoogleCredentials credentials =
58+
ServiceAccountCredentials.getApplicationDefault()
59+
.createScoped(
60+
ImmutableSet.of(
61+
"https://www.googleapis.com/auth/bigquery",
62+
"https://www.googleapis.com/auth/drive"));
63+
64+
// Initialize client that will be used to send requests. This client only needs to be created
65+
// once, and can be reused for multiple requests.
66+
BigQuery bigquery =
67+
BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
68+
69+
// Skip header row in the file.
70+
GoogleSheetsOptions sheetsOptions =
71+
GoogleSheetsOptions.newBuilder()
72+
.setSkipLeadingRows(1) // Optionally skip header row.
73+
.setRange("us-states!A20:B49") // Optionally set range of the sheet to query from.
74+
.build();
75+
76+
// Configure the external data source and query job.
77+
ExternalTableDefinition externalTable =
78+
ExternalTableDefinition.newBuilder(sourceUri, sheetsOptions).setSchema(schema).build();
79+
QueryJobConfiguration queryConfig =
80+
QueryJobConfiguration.newBuilder(query)
81+
.addTableDefinition(tableName, externalTable)
82+
.build();
83+
84+
// Example query to find states starting with 'W'
85+
TableResult results = bigquery.query(queryConfig);
86+
87+
results
88+
.iterateAll()
89+
.forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
90+
91+
System.out.println("Query on external temporary table performed successfully.");
92+
} catch (BigQueryException | InterruptedException | IOException e) {
93+
System.out.println("Query not performed \n" + e.toString());
94+
}
95+
}
96+
}
97+
// [END bigquery_query_external_sheets_temp]
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.bigquery;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
21+
import com.google.cloud.bigquery.Field;
22+
import com.google.cloud.bigquery.Schema;
23+
import com.google.cloud.bigquery.StandardSQLTypeName;
24+
import java.io.ByteArrayOutputStream;
25+
import java.io.PrintStream;
26+
import java.util.UUID;
27+
import org.junit.After;
28+
import org.junit.Before;
29+
import org.junit.Test;
30+
31+
public class QueryExternalSheetsTempIT {
32+
33+
private ByteArrayOutputStream bout;
34+
private PrintStream out;
35+
36+
@Before
37+
public void setUp() {
38+
bout = new ByteArrayOutputStream();
39+
out = new PrintStream(bout);
40+
System.setOut(out);
41+
}
42+
43+
@After
44+
public void tearDown() {
45+
System.setOut(null);
46+
}
47+
48+
@Test
49+
public void testQueryExternalSheetsTemp() {
50+
String tableName =
51+
"EXTERNAL_SHEET_TEMP_TABLE_FROM_GCS_TEST_" + UUID.randomUUID().toString().substring(0, 8);
52+
String sourceUri =
53+
"https://docs.google.com/spreadsheets/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing";
54+
Schema schema =
55+
Schema.of(
56+
Field.of("name", StandardSQLTypeName.STRING),
57+
Field.of("post_abbr", StandardSQLTypeName.STRING));
58+
String query = String.format("SELECT * FROM %s WHERE name LIKE 'W%%'", tableName);
59+
QueryExternalSheetsTemp.queryExternalSheetsTemp(tableName, sourceUri, schema, query);
60+
assertThat(bout.toString())
61+
.contains("Query on external temporary table performed successfully.");
62+
}
63+
}

0 commit comments

Comments
 (0)