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.xmlfile:
<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
BigQueryobject 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 a Google BigQuery URL?
- How can I use Google BigQuery to access Wikipedia data?
- How can I use Google Big Query to count the number of zeros in a given dataset?
- How do I use wildcards in Google BigQuery?
- How can I compare Google BigQuery, Snowflake, and Redshift for software development?
- How do I limit the results of a query in Google Big Query?
- How do Google BigQuery and MySQL compare in terms of performance and scalability?
- How can I determine the length of a string in Google BigQuery?
- How can I use Google BigQuery to retrieve data from a specific year?
See more codes...