use of com.google.cloud.bigquery.TableResult in project java-docs-samples by GoogleCloudPlatform.
the class BigQueryRunner method runQuery.
public void runQuery() throws InterruptedException {
// [START bigquery_logging_query]
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder("SELECT " + "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, " + "view_count " + "FROM `bigquery-public-data.stackoverflow.posts_questions` " + "WHERE tags like '%google-bigquery%' " + "ORDER BY favorite_count DESC LIMIT 10").setUseLegacySql(false).build();
List<TimeSeries> timeSeriesList = new ArrayList<>();
long queryStartTime = System.currentTimeMillis();
// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
// Wait for the query to complete.
queryJob = queryJob.waitFor();
// Check for errors
if (queryJob == null) {
throw new RuntimeException("Job no longer exists");
} else if (queryJob.getStatus().getError() != null) {
// errors, not just the latest one.
throw new RuntimeException(queryJob.getStatus().getError().toString());
}
// [END bigquery_logging_query]
// [START bigquery_logging_log_metrics]
// Log the result metrics.
TableResult result = queryJob.getQueryResults();
long queryEndTime = System.currentTimeMillis();
// Add query duration metric.
timeSeriesList.add(prepareMetric(QUERY_DURATION_METRIC, queryEndTime - queryStartTime));
// Add rows returned metric.
timeSeriesList.add(prepareMetric(ROWS_RETURNED_METRIC, result.getTotalRows()));
// Prepares the time series request
CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder().setName(projectName).addAllTimeSeries(timeSeriesList).build();
createMetricsIfNeeded();
client.createTimeSeries(request);
os.println("Done writing metrics.");
// [END bigquery_logging_log_metrics]
mostRecentRunResult = result;
}
Aggregations