|
| 1 | +/* |
| 2 | + * Copyright 2023 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.bigquerystorage; |
| 18 | + |
| 19 | +import com.google.api.core.ApiFuture; |
| 20 | +import com.google.api.core.ApiFutureCallback; |
| 21 | +import com.google.api.core.ApiFutures; |
| 22 | +import com.google.cloud.bigquery.BigQuery; |
| 23 | +import com.google.cloud.bigquery.BigQueryException; |
| 24 | +import com.google.cloud.bigquery.BigQueryOptions; |
| 25 | +import com.google.cloud.bigquery.QueryJobConfiguration; |
| 26 | +import com.google.cloud.bigquery.storage.v1.AppendRowsResponse; |
| 27 | +import com.google.cloud.bigquery.storage.v1.JsonStreamWriter; |
| 28 | +import com.google.cloud.bigquery.storage.v1.TableFieldSchema; |
| 29 | +import com.google.cloud.bigquery.storage.v1.TableFieldSchema.Mode; |
| 30 | +import com.google.cloud.bigquery.storage.v1.TableName; |
| 31 | +import com.google.cloud.bigquery.storage.v1.TableSchema; |
| 32 | +import com.google.common.util.concurrent.MoreExecutors; |
| 33 | +import com.google.protobuf.Descriptors.DescriptorValidationException; |
| 34 | +import java.io.BufferedReader; |
| 35 | +import java.io.FileNotFoundException; |
| 36 | +import java.io.FileReader; |
| 37 | +import java.io.IOException; |
| 38 | +import org.json.JSONArray; |
| 39 | +import org.json.JSONObject; |
| 40 | + |
| 41 | +public class JsonWriterStreamCdc { |
| 42 | + |
| 43 | + private static final String CHANGE_TYPE_PSEUDO_COLUMN = "_change_type"; |
| 44 | + |
| 45 | + private static final String CREATE_TABLE_QUERY = |
| 46 | + "CREATE TABLE `%s.%s` (\n" |
| 47 | + + " Customer_ID INT64 PRIMARY KEY NOT ENFORCED,\n" |
| 48 | + + " Customer_Enrollment_Date DATE,\n" |
| 49 | + + " Customer_Name STRING,\n" |
| 50 | + + " Customer_Address STRING,\n" |
| 51 | + + " Customer_Tier STRING,\n" |
| 52 | + + " Active_Subscriptions JSON)\n" |
| 53 | + + "OPTIONS(max_staleness = INTERVAL 15 MINUTE);"; |
| 54 | + |
| 55 | + private static final String ALTER_TABLE_QUERY = |
| 56 | + "ALTER TABLE `%s.%s`\n" + "SET OPTIONS (\n" + " max_staleness = INTERVAL 0 MINUTE);\n"; |
| 57 | + |
| 58 | + public static void main(String[] args) throws Exception { |
| 59 | + // This sample follows the BigQuery change data capture (CDC) blog post that can be found at: |
| 60 | + // https://cloud.google.com/blog/products/data-analytics/bigquery-gains-change-data-capture-functionality |
| 61 | + if (args.length != 5) { |
| 62 | + System.out.println( |
| 63 | + "Arguments: project, dataset, table, new_customers_data_file, " |
| 64 | + + "modified_customers_data_file"); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + final String projectId = args[0]; |
| 69 | + final String datasetName = args[1]; |
| 70 | + final String tableName = args[2]; |
| 71 | + final String newCustomersDataFile = args[3]; |
| 72 | + final String modifiedCustomersDataFile = args[4]; |
| 73 | + |
| 74 | + // Creates a destination table with (max_staleness = INTERVAL 15 MINUTE). |
| 75 | + createDestinationTable(datasetName, tableName); |
| 76 | + |
| 77 | + // Write new customer records to the destination table using UPSERT. |
| 78 | + JSONArray newCustomersRecords = getRecordsFromDataFile(newCustomersDataFile); |
| 79 | + writeToDefaultStream(projectId, datasetName, tableName, newCustomersRecords); |
| 80 | + |
| 81 | + // Alter the destination table so that (max_staleness = INTERVAL 0 MINUTE). |
| 82 | + alterDestinationTable(datasetName, tableName); |
| 83 | + |
| 84 | + // Modify the customer records in the destination table using UPSERT. |
| 85 | + JSONArray modifiedCustomersRecords = getRecordsFromDataFile(modifiedCustomersDataFile); |
| 86 | + writeToDefaultStream(projectId, datasetName, tableName, modifiedCustomersRecords); |
| 87 | + } |
| 88 | + |
| 89 | + public static void createDestinationTable(String datasetName, String tableName) { |
| 90 | + query(String.format(CREATE_TABLE_QUERY, datasetName, tableName)); |
| 91 | + } |
| 92 | + |
| 93 | + public static void alterDestinationTable(String datasetName, String tableName) { |
| 94 | + query(String.format(ALTER_TABLE_QUERY, datasetName, tableName)); |
| 95 | + } |
| 96 | + |
| 97 | + private static void query(String query) { |
| 98 | + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); |
| 99 | + QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query).build(); |
| 100 | + try { |
| 101 | + bigquery.query(queryConfig); |
| 102 | + } catch (BigQueryException | InterruptedException e) { |
| 103 | + System.out.println("Query did not run \n" + e.toString()); |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + // writeToDefaultStream: Writes records from the source file to the destination table. |
| 108 | + public static void writeToDefaultStream( |
| 109 | + String projectId, String datasetName, String tableName, JSONArray data) |
| 110 | + throws DescriptorValidationException, InterruptedException, IOException { |
| 111 | + // To use the UPSERT functionality, the table schema needs to be padded with an additional |
| 112 | + // column "_change_type". |
| 113 | + TableSchema tableSchema = |
| 114 | + TableSchema.newBuilder() |
| 115 | + .addFields( |
| 116 | + TableFieldSchema.newBuilder() |
| 117 | + .setName("Customer_ID") |
| 118 | + .setType(TableFieldSchema.Type.INT64) |
| 119 | + .setMode(Mode.NULLABLE) |
| 120 | + .build()) |
| 121 | + .addFields( |
| 122 | + TableFieldSchema.newBuilder() |
| 123 | + .setName("Customer_Enrollment_Date") |
| 124 | + .setType(TableFieldSchema.Type.DATE) |
| 125 | + .setMode(Mode.NULLABLE) |
| 126 | + .build()) |
| 127 | + .addFields( |
| 128 | + TableFieldSchema.newBuilder() |
| 129 | + .setName("Customer_Name") |
| 130 | + .setType(TableFieldSchema.Type.STRING) |
| 131 | + .setMode(Mode.NULLABLE) |
| 132 | + .build()) |
| 133 | + .addFields( |
| 134 | + TableFieldSchema.newBuilder() |
| 135 | + .setName("Customer_Address") |
| 136 | + .setType(TableFieldSchema.Type.STRING) |
| 137 | + .setMode(Mode.NULLABLE) |
| 138 | + .build()) |
| 139 | + .addFields( |
| 140 | + TableFieldSchema.newBuilder() |
| 141 | + .setName("Customer_Tier") |
| 142 | + .setType(TableFieldSchema.Type.STRING) |
| 143 | + .setMode(Mode.NULLABLE) |
| 144 | + .build()) |
| 145 | + .addFields( |
| 146 | + TableFieldSchema.newBuilder() |
| 147 | + .setName("Active_Subscriptions") |
| 148 | + .setType(TableFieldSchema.Type.JSON) |
| 149 | + .setMode(Mode.NULLABLE) |
| 150 | + .build()) |
| 151 | + .addFields( |
| 152 | + TableFieldSchema.newBuilder() |
| 153 | + .setName(CHANGE_TYPE_PSEUDO_COLUMN) |
| 154 | + .setType(TableFieldSchema.Type.STRING) |
| 155 | + .setMode(Mode.NULLABLE) |
| 156 | + .build()) |
| 157 | + .build(); |
| 158 | + |
| 159 | + // Use the JSON stream writer to send records in JSON format. |
| 160 | + TableName parentTable = TableName.of(projectId, datasetName, tableName); |
| 161 | + try (JsonStreamWriter writer = |
| 162 | + JsonStreamWriter.newBuilder(parentTable.toString(), tableSchema).build()) { |
| 163 | + |
| 164 | + ApiFuture<AppendRowsResponse> future = writer.append(data); |
| 165 | + // The append method is asynchronous. Rather than waiting for the method to complete, |
| 166 | + // which can hurt performance, register a completion callback and continue streaming. |
| 167 | + ApiFutures.addCallback(future, new AppendCompleteCallback(), MoreExecutors.directExecutor()); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + public static JSONArray getRecordsFromDataFile(String dataFile) |
| 172 | + throws FileNotFoundException, IOException { |
| 173 | + JSONArray result = new JSONArray(); |
| 174 | + |
| 175 | + BufferedReader reader = new BufferedReader(new FileReader(dataFile)); |
| 176 | + String line = reader.readLine(); |
| 177 | + while (line != null) { |
| 178 | + JSONObject record = new JSONObject(line); |
| 179 | + result.put(record); |
| 180 | + line = reader.readLine(); |
| 181 | + } |
| 182 | + |
| 183 | + return result; |
| 184 | + } |
| 185 | + |
| 186 | + static class AppendCompleteCallback implements ApiFutureCallback<AppendRowsResponse> { |
| 187 | + private static final Object lock = new Object(); |
| 188 | + private static int batchCount = 0; |
| 189 | + |
| 190 | + public void onSuccess(AppendRowsResponse response) { |
| 191 | + synchronized (lock) { |
| 192 | + if (response.hasError()) { |
| 193 | + System.out.format("Error: %s\n", response.getError()); |
| 194 | + } else { |
| 195 | + ++batchCount; |
| 196 | + System.out.format("Wrote batch %d\n", batchCount); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + public void onFailure(Throwable throwable) { |
| 202 | + System.out.format("Error: %s\n", throwable.toString()); |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments