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
- ¿Cuáles son las ventajas y desventajas de usar Google BigQuery?
- How do I use the YEAR function in Google BigQuery?
- How can I export data from Google Big Query to an XLSX file?
- How can I use the CASE WHEN statement in Google Big Query?
- How can I learn to use Google BigQuery?
- How can I use Google BigQuery to access Wikipedia data?
- How do I use wildcards in Google BigQuery?
- How can I compare Google BigQuery, Snowflake, and Redshift for software development?
- How can I get started with Google BigQuery training?
- How can I use Google Big Query with Grafana to visualize data?
See more codes...