Search in sources :

Example 16 with TableName

use of com.google.bigtable.admin.v2.TableName in project java-bigquerystorage by googleapis.

the class WriteCommittedStream method writeCommittedStream.

public static void writeCommittedStream(String projectId, String datasetName, String tableName) throws DescriptorValidationException, InterruptedException, IOException {
    try (BigQueryWriteClient client = BigQueryWriteClient.create()) {
        // Initialize a write stream for the specified table.
        // For more information on WriteStream.Type, see:
        // https://googleapis.dev/java/google-cloud-bigquerystorage/latest/com/google/cloud/bigquery/storage/v1beta2/WriteStream.Type.html
        WriteStream stream = WriteStream.newBuilder().setType(WriteStream.Type.COMMITTED).build();
        TableName parentTable = TableName.of(projectId, datasetName, tableName);
        CreateWriteStreamRequest createWriteStreamRequest = CreateWriteStreamRequest.newBuilder().setParent(parentTable.toString()).setWriteStream(stream).build();
        WriteStream writeStream = client.createWriteStream(createWriteStreamRequest);
        // https://googleapis.dev/java/google-cloud-bigquerystorage/latest/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.html
        try (JsonStreamWriter writer = JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema()).build()) {
            // antipattern.
            for (int i = 0; i < 2; i++) {
                // Create a JSON object that is compatible with the table schema.
                JSONArray jsonArr = new JSONArray();
                for (int j = 0; j < 10; j++) {
                    JSONObject record = new JSONObject();
                    record.put("col1", String.format("record %03d-%03d", i, j));
                    jsonArr.put(record);
                }
                // To detect duplicate records, pass the index as the record offset.
                // To disable deduplication, omit the offset or use WriteStream.Type.DEFAULT.
                ApiFuture<AppendRowsResponse> future = writer.append(jsonArr, /*offset=*/
                i * 10);
                AppendRowsResponse response = future.get();
            }
            // Finalize the stream after use.
            FinalizeWriteStreamRequest finalizeWriteStreamRequest = FinalizeWriteStreamRequest.newBuilder().setName(writeStream.getName()).build();
            client.finalizeWriteStream(finalizeWriteStreamRequest);
        }
        System.out.println("Appended records successfully.");
    } catch (ExecutionException e) {
        // If the wrapped exception is a StatusRuntimeException, check the state of the operation.
        // If the state is INTERNAL, CANCELLED, or ABORTED, you can retry. For more information, see:
        // https://grpc.github.io/grpc-java/javadoc/io/grpc/StatusRuntimeException.html
        System.out.println("Failed to append records. \n" + e.toString());
    }
}
Also used : TableName(com.google.cloud.bigquery.storage.v1.TableName) CreateWriteStreamRequest(com.google.cloud.bigquery.storage.v1.CreateWriteStreamRequest) FinalizeWriteStreamRequest(com.google.cloud.bigquery.storage.v1.FinalizeWriteStreamRequest) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) AppendRowsResponse(com.google.cloud.bigquery.storage.v1.AppendRowsResponse) WriteStream(com.google.cloud.bigquery.storage.v1.WriteStream) BigQueryWriteClient(com.google.cloud.bigquery.storage.v1.BigQueryWriteClient) ExecutionException(java.util.concurrent.ExecutionException) JsonStreamWriter(com.google.cloud.bigquery.storage.v1.JsonStreamWriter)

Example 17 with TableName

use of com.google.bigtable.admin.v2.TableName in project java-bigquerystorage by googleapis.

the class WriteToDefaultStream method writeToDefaultStream.

public static void writeToDefaultStream(String projectId, String datasetName, String tableName) throws DescriptorValidationException, InterruptedException, IOException {
    BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    Table table = bigquery.getTable(datasetName, tableName);
    TableName parentTable = TableName.of(projectId, datasetName, tableName);
    Schema schema = table.getDefinition().getSchema();
    TableSchema tableSchema = BqToBqStorageSchemaConverter.convertTableSchema(schema);
    // https://googleapis.dev/java/google-cloud-bigquerystorage/latest/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.html
    try (JsonStreamWriter writer = JsonStreamWriter.newBuilder(parentTable.toString(), tableSchema).build()) {
        // much writes as possible. Creating a writer for just one write is an antipattern.
        for (int i = 0; i < 2; i++) {
            // Create a JSON object that is compatible with the table schema.
            JSONArray jsonArr = new JSONArray();
            for (int j = 0; j < 10; j++) {
                JSONObject record = new JSONObject();
                record.put("test_string", String.format("record %03d-%03d", i, j));
                jsonArr.put(record);
            }
            ApiFuture<AppendRowsResponse> future = writer.append(jsonArr);
            AppendRowsResponse response = future.get();
        }
        System.out.println("Appended records successfully.");
    } catch (ExecutionException e) {
        // If the wrapped exception is a StatusRuntimeException, check the state of the operation.
        // If the state is INTERNAL, CANCELLED, or ABORTED, you can retry. For more information, see:
        // https://grpc.github.io/grpc-java/javadoc/io/grpc/StatusRuntimeException.html
        System.out.println("Failed to append records. \n" + e.toString());
    }
}
Also used : TableName(com.google.cloud.bigquery.storage.v1.TableName) BigQuery(com.google.cloud.bigquery.BigQuery) Table(com.google.cloud.bigquery.Table) TableSchema(com.google.cloud.bigquery.storage.v1.TableSchema) JSONObject(org.json.JSONObject) TableSchema(com.google.cloud.bigquery.storage.v1.TableSchema) Schema(com.google.cloud.bigquery.Schema) JSONArray(org.json.JSONArray) AppendRowsResponse(com.google.cloud.bigquery.storage.v1.AppendRowsResponse) ExecutionException(java.util.concurrent.ExecutionException) JsonStreamWriter(com.google.cloud.bigquery.storage.v1.JsonStreamWriter)

Example 18 with TableName

use of com.google.bigtable.admin.v2.TableName in project beam by apache.

the class BigtableClientWrapper method createTable.

void createTable(String tableName, String familyName) {
    Table.Builder tableBuilder = Table.newBuilder();
    tableBuilder.putColumnFamilies(familyName, ColumnFamily.newBuilder().build());
    String instanceName = bigtableOptions.getInstanceName().toString();
    com.google.bigtable.admin.v2.CreateTableRequest.Builder createTableRequestBuilder = com.google.bigtable.admin.v2.CreateTableRequest.newBuilder().setParent(instanceName).setTableId(tableName).setTable(tableBuilder.build());
    tableAdminClient.createTable(createTableRequestBuilder.build());
}
Also used : Table(com.google.bigtable.admin.v2.Table) RowUtils.byteString(org.apache.beam.sdk.io.gcp.bigtable.RowUtils.byteString)

Example 19 with TableName

use of com.google.bigtable.admin.v2.TableName in project beam by apache.

the class BigtableWriteIT method testE2EBigtableWrite.

@Test
public void testE2EBigtableWrite() throws Exception {
    final String tableName = bigtableOptions.getInstanceName().toTableNameStr(tableId);
    final String instanceName = bigtableOptions.getInstanceName().toString();
    final int numRows = 1000;
    final List<KV<ByteString, ByteString>> testData = generateTableData(numRows);
    createEmptyTable(instanceName, tableId);
    Pipeline p = Pipeline.create(options);
    p.apply(GenerateSequence.from(0).to(numRows)).apply(ParDo.of(new DoFn<Long, KV<ByteString, Iterable<Mutation>>>() {

        @ProcessElement
        public void processElement(ProcessContext c) {
            int index = c.element().intValue();
            Iterable<Mutation> mutations = ImmutableList.of(Mutation.newBuilder().setSetCell(Mutation.SetCell.newBuilder().setValue(testData.get(index).getValue()).setFamilyName(COLUMN_FAMILY_NAME)).build());
            c.output(KV.of(testData.get(index).getKey(), mutations));
        }
    })).apply(BigtableIO.write().withBigtableOptions(bigtableOptions).withTableId(tableId));
    p.run();
    // Test number of column families and column family name equality
    Table table = getTable(tableName);
    assertThat(table.getColumnFamiliesMap().keySet(), Matchers.hasSize(1));
    assertThat(table.getColumnFamiliesMap(), Matchers.hasKey(COLUMN_FAMILY_NAME));
    // Test table data equality
    List<KV<ByteString, ByteString>> tableData = getTableData(tableName);
    assertThat(tableData, Matchers.containsInAnyOrder(testData.toArray()));
}
Also used : Table(com.google.bigtable.admin.v2.Table) ByteString(com.google.protobuf.ByteString) KV(org.apache.beam.sdk.values.KV) Mutation(com.google.bigtable.v2.Mutation) TestPipeline(org.apache.beam.sdk.testing.TestPipeline) Pipeline(org.apache.beam.sdk.Pipeline) Test(org.junit.Test)

Example 20 with TableName

use of com.google.bigtable.admin.v2.TableName in project java-bigtable by googleapis.

the class BigtableTableAdminClientTest method testAwaitReplication.

@Test
public void testAwaitReplication() {
    // Setup
    Mockito.when(mockStub.awaitReplicationCallable()).thenReturn(mockAwaitReplicationCallable);
    TableName expectedRequest = TableName.parse(TABLE_NAME);
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    Mockito.when(mockAwaitReplicationCallable.futureCall(expectedRequest)).thenAnswer((Answer<ApiFuture<Void>>) invocationOnMock -> {
        wasCalled.set(true);
        return ApiFutures.immediateFuture(null);
    });
    // Execute
    adminClient.awaitReplication(TABLE_ID);
    // Verify
    assertThat(wasCalled.get()).isTrue();
}
Also used : ArgumentMatchers(org.mockito.ArgumentMatchers) OperationFuture(com.google.api.gax.longrunning.OperationFuture) NotFoundException(com.google.api.gax.rpc.NotFoundException) CreateBackupMetadata(com.google.bigtable.admin.v2.CreateBackupMetadata) ListTablesRequest(com.google.bigtable.admin.v2.ListTablesRequest) Empty(com.google.protobuf.Empty) Table(com.google.cloud.bigtable.admin.v2.models.Table) ColumnFamily(com.google.bigtable.admin.v2.ColumnFamily) Map(java.util.Map) CreateTableRequest(com.google.cloud.bigtable.admin.v2.models.CreateTableRequest) Status(io.grpc.Status) Backup(com.google.cloud.bigtable.admin.v2.models.Backup) GcRule(com.google.bigtable.admin.v2.GcRule) Role(com.google.cloud.Role) ListBackupsPage(com.google.cloud.bigtable.admin.v2.BaseBigtableTableAdminClient.ListBackupsPage) ListTablesPagedResponse(com.google.cloud.bigtable.admin.v2.BaseBigtableTableAdminClient.ListTablesPagedResponse) ApiFutures(com.google.api.core.ApiFutures) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) Timestamps(com.google.protobuf.util.Timestamps) ClusterState(com.google.bigtable.admin.v2.Table.ClusterState) State(com.google.bigtable.admin.v2.Backup.State) ListTablesPage(com.google.cloud.bigtable.admin.v2.BaseBigtableTableAdminClient.ListTablesPage) ApiFuture(com.google.api.core.ApiFuture) ByteString(com.google.protobuf.ByteString) EncryptionInfo(com.google.cloud.bigtable.admin.v2.models.EncryptionInfo) List(java.util.List) DeleteTableRequest(com.google.bigtable.admin.v2.DeleteTableRequest) NameUtil(com.google.cloud.bigtable.admin.v2.internal.NameUtil) RestoreTableMetadata(com.google.bigtable.admin.v2.RestoreTableMetadata) DeleteBackupRequest(com.google.bigtable.admin.v2.DeleteBackupRequest) GetTableRequest(com.google.bigtable.admin.v2.GetTableRequest) BackupInfo(com.google.bigtable.admin.v2.BackupInfo) Policy(com.google.cloud.Policy) Mock(org.mockito.Mock) OperationFutures(com.google.api.gax.longrunning.OperationFutures) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Operation(com.google.longrunning.Operation) Timestamp(com.google.protobuf.Timestamp) RestoreSourceType(com.google.bigtable.admin.v2.RestoreSourceType) CreateBackupRequest(com.google.cloud.bigtable.admin.v2.models.CreateBackupRequest) Code(io.grpc.Status.Code) Answer(org.mockito.stubbing.Answer) ListBackupsPagedResponse(com.google.cloud.bigtable.admin.v2.BaseBigtableTableAdminClient.ListBackupsPagedResponse) Lists(com.google.common.collect.Lists) RestoreTableRequest(com.google.cloud.bigtable.admin.v2.models.RestoreTableRequest) ImmutableList(com.google.common.collect.ImmutableList) GrpcStatusCode(com.google.api.gax.grpc.GrpcStatusCode) Instant(org.threeten.bp.Instant) RestoredTableResult(com.google.cloud.bigtable.admin.v2.models.RestoredTableResult) MockitoJUnit(org.mockito.junit.MockitoJUnit) ModifyColumnFamiliesRequest(com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest) Identity(com.google.cloud.Identity) Modification(com.google.bigtable.admin.v2.ModifyColumnFamiliesRequest.Modification) Before(org.junit.Before) EnhancedBigtableTableAdminStub(com.google.cloud.bigtable.admin.v2.stub.EnhancedBigtableTableAdminStub) BaseEncoding(com.google.common.io.BaseEncoding) UpdateBackupRequest(com.google.cloud.bigtable.admin.v2.models.UpdateBackupRequest) Test(org.junit.Test) DropRowRangeRequest(com.google.bigtable.admin.v2.DropRowRangeRequest) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) View(com.google.bigtable.admin.v2.Table.View) TableName(com.google.bigtable.admin.v2.TableName) ExecutionException(java.util.concurrent.ExecutionException) OperationCallable(com.google.api.gax.rpc.OperationCallable) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) ListBackupsRequest(com.google.bigtable.admin.v2.ListBackupsRequest) MockitoRule(org.mockito.junit.MockitoRule) FakeOperationSnapshot(com.google.api.gax.rpc.testing.FakeOperationSnapshot) GetBackupRequest(com.google.bigtable.admin.v2.GetBackupRequest) TableName(com.google.bigtable.admin.v2.TableName) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ApiFuture(com.google.api.core.ApiFuture) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)36 ByteString (com.google.protobuf.ByteString)31 ArrayList (java.util.ArrayList)20 TableName (com.google.bigtable.v2.TableName)18 TableName (com.google.bigtable.admin.v2.TableName)17 InvalidArgumentException (com.google.api.gax.rpc.InvalidArgumentException)13 Mutation (com.google.bigtable.v2.Mutation)13 AbstractMessage (com.google.protobuf.AbstractMessage)13 StatusRuntimeException (io.grpc.StatusRuntimeException)13 JSONArray (org.json.JSONArray)9 JSONObject (org.json.JSONObject)9 ExecutionException (java.util.concurrent.ExecutionException)8 TableName (com.google.cloud.bigquery.storage.v1.TableName)7 ReadModifyWriteRule (com.google.bigtable.v2.ReadModifyWriteRule)6 RowFilter (com.google.bigtable.v2.RowFilter)6 BaseBigtableDataClient (com.google.cloud.bigtable.data.v2.BaseBigtableDataClient)6 ColumnFamily (com.google.bigtable.admin.v2.ColumnFamily)5 Table (com.google.bigtable.admin.v2.Table)4 CheckAndMutateRowResponse (com.google.bigtable.v2.CheckAndMutateRowResponse)4 ReadModifyWriteRowResponse (com.google.bigtable.v2.ReadModifyWriteRowResponse)4