forked from GoogleCloudPlatform/java-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryParametersSample.java
More file actions
284 lines (252 loc) · 10 KB
/
Copy pathQueryParametersSample.java
File metadata and controls
284 lines (252 loc) · 10 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.bigquery;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.FieldValue;
import com.google.cloud.bigquery.QueryParameterValue;
import com.google.cloud.bigquery.QueryRequest;
import com.google.cloud.bigquery.QueryResponse;
import com.google.cloud.bigquery.QueryResult;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* A sample that demonstrates use of query parameters.
*/
public class QueryParametersSample {
private static final int ERROR_CODE = 1;
private static void printUsage() {
System.err.println("Usage:");
System.err.printf(
"\tmvn exec:java -Dexec.mainClass=%s -Dexec.args='%s'\n",
QueryParametersSample.class.getCanonicalName(),
"${sample}");
System.err.println();
System.err.println("${sample} can be one of: named, array, timestamp");
System.err.println();
System.err.println("Usage for ${sample}=named:");
System.err.printf(
"\tmvn exec:java -Dexec.mainClass=%s -Dexec.args='%s'\n",
QueryParametersSample.class.getCanonicalName(),
"named ${corpus} ${minWordCount}");
System.err.println();
System.err.println("Usage for sample=array:");
System.err.printf(
"\tmvn exec:java -Dexec.mainClass=%s -Dexec.args='%s'\n",
QueryParametersSample.class.getCanonicalName(),
"array ${gender} ${states...}");
System.err.println();
System.err.println("\twhere ${gender} can be on of: M, F");
System.err.println(
"\tand ${states} is any upper-case 2-letter code for U.S. a state, e.g. CA.");
System.err.println();
System.err.printf(
"\t\tmvn exec:java -Dexec.mainClass=%s -Dexec.args='%s'\n",
QueryParametersSample.class.getCanonicalName(),
"array F MD WA");
}
/**
* Prompts the user for the required parameters to perform a query.
*/
public static void main(final String[] args) throws IOException, InterruptedException {
if (args.length < 1) {
System.err.println("Expected first argument 'sample'");
printUsage();
System.exit(ERROR_CODE);
}
String sample = args[0];
switch (sample) {
case "named":
if (args.length != 3) {
System.err.println("Unexpected number of arguments for named query sample.");
printUsage();
System.exit(ERROR_CODE);
}
runNamed(args[1], Long.parseLong(args[2]));
break;
case "array":
if (args.length < 2) {
System.err.println("Unexpected number of arguments for array query sample.");
printUsage();
System.exit(ERROR_CODE);
}
String gender = args[1];
String[] states = Arrays.copyOfRange(args, 2, args.length);
runArray(gender, states);
break;
case "timestamp":
if (args.length != 1) {
System.err.println("Unexpected number of arguments for timestamp query sample.");
printUsage();
System.exit(ERROR_CODE);
}
runTimestamp();
break;
default:
System.err.println("Got bad value for sample");
printUsage();
System.exit(ERROR_CODE);
}
}
/**
* Query the Shakespeare dataset for words with count at least {@code minWordCount} in the corpus
* {@code corpus}.
*/
// [START bigquery_query_params]
private static void runNamed(final String corpus, final long minWordCount)
throws InterruptedException {
BigQuery bigquery =
new BigQueryOptions.DefaultBigqueryFactory().create(BigQueryOptions.getDefaultInstance());
String queryString = "SELECT word, word_count\n"
+ "FROM `bigquery-public-data.samples.shakespeare`\n"
+ "WHERE corpus = @corpus\n"
+ "AND word_count >= @min_word_count\n"
+ "ORDER BY word_count DESC";
QueryRequest queryRequest =
QueryRequest.newBuilder(queryString)
.addNamedParameter("corpus", QueryParameterValue.string(corpus))
.addNamedParameter("min_word_count", QueryParameterValue.int64(minWordCount))
// Standard SQL syntax is required for parameterized queries.
// See: https://cloud.google.com/bigquery/sql-reference/
.setUseLegacySql(false)
.build();
// Execute the query.
QueryResponse response = bigquery.query(queryRequest);
// Wait for the job to finish (if the query takes more than 10 seconds to complete).
while (!response.jobCompleted()) {
Thread.sleep(1000);
response = bigquery.getQueryResults(response.getJobId());
}
if (response.hasErrors()) {
throw new RuntimeException(
response
.getExecutionErrors()
.stream()
.<String>map(err -> err.getMessage())
.collect(Collectors.joining("\n")));
}
QueryResult result = response.getResult();
Iterator<List<FieldValue>> iter = result.iterateAll();
while (iter.hasNext()) {
List<FieldValue> row = iter.next();
System.out.printf(
"%s: %d\n",
row.get(0).getStringValue(),
row.get(1).getLongValue());
}
}
// [END bigquery_query_params]
/**
* Query the baby names database to find the most popular names for a gender in a list of states.
*/
// [START bigquery_query_params_arrays]
private static void runArray(String gender, String[] states)
throws InterruptedException {
BigQuery bigquery =
new BigQueryOptions.DefaultBigqueryFactory().create(BigQueryOptions.getDefaultInstance());
String queryString = "SELECT name, sum(number) as count\n"
+ "FROM `bigquery-public-data.usa_names.usa_1910_2013`\n"
+ "WHERE gender = @gender\n"
+ "AND state IN UNNEST(@states)\n"
+ "GROUP BY name\n"
+ "ORDER BY count DESC\n"
+ "LIMIT 10;";
QueryRequest queryRequest =
QueryRequest.newBuilder(queryString)
.addNamedParameter("gender", QueryParameterValue.string(gender))
.addNamedParameter(
"states",
QueryParameterValue.array(states, String.class))
// Standard SQL syntax is required for parameterized queries.
// See: https://cloud.google.com/bigquery/sql-reference/
.setUseLegacySql(false)
.build();
// Execute the query.
QueryResponse response = bigquery.query(queryRequest);
// Wait for the job to finish (if the query takes more than 10 seconds to complete).
while (!response.jobCompleted()) {
Thread.sleep(1000);
response = bigquery.getQueryResults(response.getJobId());
}
if (response.hasErrors()) {
throw new RuntimeException(
response
.getExecutionErrors()
.stream()
.<String>map(err -> err.getMessage())
.collect(Collectors.joining("\n")));
}
QueryResult result = response.getResult();
Iterator<List<FieldValue>> iter = result.iterateAll();
while (iter.hasNext()) {
List<FieldValue> row = iter.next();
System.out.printf("%s: %d\n", row.get(0).getStringValue(), row.get(1).getLongValue());
}
}
// [END bigquery_query_params_arrays]
// [START bigquery_query_params_timestamps]
private static void runTimestamp() throws InterruptedException {
BigQuery bigquery =
new BigQueryOptions.DefaultBigqueryFactory().create(BigQueryOptions.getDefaultInstance());
DateTime timestamp = new DateTime(2016, 12, 7, 8, 0, 0, DateTimeZone.UTC);
String queryString = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);";
QueryRequest queryRequest =
QueryRequest.newBuilder(queryString)
.addNamedParameter(
"ts_value",
QueryParameterValue.timestamp(
// Timestamp takes microseconds since 1970-01-01T00:00:00 UTC
timestamp.getMillis() * 1000))
// Standard SQL syntax is required for parameterized queries.
// See: https://cloud.google.com/bigquery/sql-reference/
.setUseLegacySql(false)
.build();
// Execute the query.
QueryResponse response = bigquery.query(queryRequest);
// Wait for the job to finish (if the query takes more than 10 seconds to complete).
while (!response.jobCompleted()) {
Thread.sleep(1000);
response = bigquery.getQueryResults(response.getJobId());
}
if (response.hasErrors()) {
throw new RuntimeException(
response
.getExecutionErrors()
.stream()
.<String>map(err -> err.getMessage())
.collect(Collectors.joining("\n")));
}
QueryResult result = response.getResult();
Iterator<List<FieldValue>> iter = result.iterateAll();
DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis().withZoneUTC();
while (iter.hasNext()) {
List<FieldValue> row = iter.next();
System.out.printf(
"%s\n",
formatter.print(
new DateTime(
// Timestamp values are returned in microseconds since 1970-01-01T00:00:00 UTC,
// but org.joda.time.DateTime constructor accepts times in milliseconds.
row.get(0).getTimestampValue() / 1000,
DateTimeZone.UTC)));
}
}
// [END bigquery_query_params_timestamps]
}