Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(samples): add query external bigtable using temp table #763

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1,110 @@
/*
* Copyright 2020 Google LLC
*
* 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;

// [START bigquery_query_external_bigtable_temp]
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.BigtableColumn;
import com.google.cloud.bigquery.BigtableColumnFamily;
import com.google.cloud.bigquery.BigtableOptions;
import com.google.cloud.bigquery.ExternalTableDefinition;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.TableResult;
import com.google.common.collect.ImmutableList;
import org.apache.commons.codec.binary.Base64;

// Sample to queries an external bigtable data source using a temporary table
public class QueryExternalBigtableTemp {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
String projectId = "MY_PROJECT_ID";
String instanceId = "MY_INSTANCE_ID";
String bigtableName = "MY_BIGTABLE_NAME";
String tableName = "MY_TABLE_NAME";
String sourceUri =
"https://googleapis.com/bigtable/projects/"
+ projectId
+ "/instances/"
+ instanceId
+ "/tables/"
+ bigtableName;
String query = String.format("SELECT * FROM %s ", tableName);
queryExternalBigtableTemp(tableName, sourceUri, query);
}

public static void queryExternalBigtableTemp(String tableName, String sourceUri, String query) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have a sample schema for bigtable we've been using that would be good to include here so it feels a little more realistic. I'll send you a doc with the schema

table name: mobile-time-series
column families: stats_summary
columns: os_build (STRING), os_name (STRING)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://github.com/googleapis/java-bigtable/blob/master/samples/snippets/src/test/java/com/example/bigtable/ReadsTest.java
Let's stick to the existing table schema as shown above instead of using our own schema and stream in data in the beforeClass() method. We can keep the table name as bigquery-samples-test

try {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests.
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

BigtableColumn name =
BigtableColumn.newBuilder()
.setQualifierEncoded(Base64.encodeBase64String("name".getBytes()))
.setFieldName("name")
.setType("STRING")
.setEncoding("TEXT")
.build();
BigtableColumn postAbbr =
BigtableColumn.newBuilder()
.setQualifierEncoded(Base64.encodeBase64String("post_abbr".getBytes()))
.setFieldName("post_abbr")
.setType("STRING")
.setEncoding("TEXT")
.build();
BigtableColumnFamily usStates =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you define the column family first and then add the columns and build after? It will make more sense for someone from Bigtable following since column families are the higher level grouping

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@billyjacobson It's not possible to main order, because first we need to create an object of BigtableColumn then we can set those columns in BigtableColumnFamily.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could first instantiate an empty BigtableColumnFamily object and then add columns to it.

BigtableColumnFamily.newBuilder()
.setColumns(ImmutableList.of(name, postAbbr))
.setFamilyID("us-states")
.setOnlyReadLatest(true)
.setEncoding("TEXT")
.setType("STRING")
.build();

// Configure BigtableOptions is optional.
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
BigtableOptions options =
BigtableOptions.newBuilder()
.setIgnoreUnspecifiedColumnFamilies(true)
.setReadRowkeyAsString(true)
.setColumnFamilies(ImmutableList.of(usStates))
.build();

// Configure the external data source and query job.
ExternalTableDefinition externalTable =
ExternalTableDefinition.newBuilder(sourceUri, options).build();
QueryJobConfiguration queryConfig =
QueryJobConfiguration.newBuilder(query)
.addTableDefinition(tableName, externalTable)
.build();

// Example query to find states starting with 'A'
TableResult results = bigquery.query(queryConfig);

results
.iterateAll()
.forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));

System.out.println("Query on external temporary table performed successfully.");
} catch (BigQueryException | InterruptedException e) {
System.out.println("Query not performed \n" + e.toString());
}
}
}
// [END bigquery_query_external_bigtable_temp]
@@ -0,0 +1,79 @@
/*
* Copyright 2020 Google LLC
*
* 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 static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class QueryExternalBigtableTempIT {

private final Logger log = Logger.getLogger(this.getClass().getName());
private ByteArrayOutputStream bout;
private PrintStream out;
private PrintStream originalPrintStream;

private static final String BIGTABLE_URI = requireEnvVar("BIGTABLE_URI");

private static String requireEnvVar(String varName) {
String value = System.getenv(varName);
assertNotNull(
"Environment variable " + varName + " is required to perform these tests.",
System.getenv(varName));
return value;
}

@BeforeClass
public static void checkRequirements() {
requireEnvVar("BIGTABLE_URI");
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
}

@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
originalPrintStream = System.out;
System.setOut(out);
}

@After
public void tearDown() {
// restores print statements in the original method
System.out.flush();
System.setOut(originalPrintStream);
log.log(Level.INFO, bout.toString());
}

@Test
public void testQueryExternalBigtableTemp() {
String tableName =
"EXTERNAL_TEMP_TABLE_FROM_BIGTABLE_TEST_" + UUID.randomUUID().toString().substring(0, 8);
String query = String.format("SELECT * FROM %s ", tableName);
QueryExternalBigtableTemp.queryExternalBigtableTemp(tableName, BIGTABLE_URI, query);
assertThat(bout.toString())
.contains("Query on external temporary table performed successfully.");
}
}