google-big-queryHow do I use the Google BigQuery API with Java?
The Google BigQuery API can be used with Java to access and manipulate data stored in Google BigQuery. To get started, you will need to set up the necessary credentials and libraries.
- Set up credentials:
- Go to the Google Cloud Platform Console and create a project, or use an existing one.
- Enable the BigQuery API.
- Create a service account and download the JSON file with the credentials.
- Install the Java BigQuery client library:
- Add the following line to your
pom.xml
file:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-bigquery</artifactId>
<version>1.94.0</version>
</dependency>
- Install the library with Maven:
mvn install
- Use the Java BigQuery client library:
- Create a
BigQuery
object with the credentials file:
BigQuery bigquery = BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
- Run a query:
String query = "SELECT word FROM `bigquery-public-data.samples.shakespeare` GROUP BY word;";
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query).build();
// 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) {
// You can also look at queryJob.getStatus().getExecutionErrors() for all
// errors, not just the latest one.
throw new RuntimeException(queryJob.getStatus().getError().toString());
}
// Get the results.
TableResult result = queryJob.getQueryResults();
- Print the results:
for (FieldValueList row : result.iterateAll()) {
String word = row.get("word").getStringValue();
System.out.println("word: " + word);
}
Output example
word: A
word: All
word: Am
word: ...
For more information, see the BigQuery Java API reference.
More of Google Big Query
- How do I rename a column in Google BigQuery?
- How can I use Google BigQuery to answer specific questions?
- How do I set up permissions for Google BigQuery?
- How can I use Google Big Query to integrate with Zephyr?
- How can I use Google BigQuery to wait for a query to complete?
- How do I use Google BigQuery Sandbox?
- What are the advantages and disadvantages of using Google BigQuery?
- How do I sign in to Google Big Query?
- How do I use Google BigQuery to understand the meaning of data?
- How can I export data from Google Big Query to an XLSX file?
See more codes...