Search in sources :

Example 1 with ReadStream

use of com.google.cloud.bigquery.storage.v1beta2.ReadStream in project java-bigquerystorage by googleapis.

the class ITBigQueryStorageLongRunningTest method readAllRowsFromStream.

private long readAllRowsFromStream(ReadStream readStream) {
    ReadRowsRequest readRowsRequest = ReadRowsRequest.newBuilder().setReadStream(readStream.getName()).build();
    long rowCount = 0;
    ServerStream<ReadRowsResponse> serverStream = client.readRowsCallable().call(readRowsRequest);
    for (ReadRowsResponse response : serverStream) {
        rowCount += response.getRowCount();
    }
    LOG.info(String.format("Read total of %d rows from stream '%s'.", rowCount, readStream.getName()));
    return rowCount;
}
Also used : ReadRowsResponse(com.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse) ReadRowsRequest(com.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest)

Example 2 with ReadStream

use of com.google.cloud.bigquery.storage.v1beta2.ReadStream in project beam by apache.

the class BigQueryStorageSourceBase method split.

@Override
public List<BigQueryStorageStreamSource<T>> split(long desiredBundleSizeBytes, PipelineOptions options) throws Exception {
    BigQueryOptions bqOptions = options.as(BigQueryOptions.class);
    Table targetTable = getTargetTable(bqOptions);
    ReadSession.Builder readSessionBuilder = ReadSession.newBuilder();
    if (targetTable != null) {
        readSessionBuilder.setTable(BigQueryHelpers.toTableResourceName(targetTable.getTableReference()));
    } else {
        // If the table does not exist targetTable will be null.
        // Construct the table id if we can generate it. For error recording/logging.
        @Nullable String tableReferenceId = getTargetTableId(bqOptions);
        if (tableReferenceId != null) {
            readSessionBuilder.setTable(tableReferenceId);
        }
    }
    if (selectedFieldsProvider != null || rowRestrictionProvider != null) {
        ReadSession.TableReadOptions.Builder tableReadOptionsBuilder = ReadSession.TableReadOptions.newBuilder();
        if (selectedFieldsProvider != null) {
            tableReadOptionsBuilder.addAllSelectedFields(selectedFieldsProvider.get());
        }
        if (rowRestrictionProvider != null) {
            tableReadOptionsBuilder.setRowRestriction(rowRestrictionProvider.get());
        }
        readSessionBuilder.setReadOptions(tableReadOptionsBuilder);
    }
    if (format != null) {
        readSessionBuilder.setDataFormat(format);
    }
    int streamCount = 0;
    if (desiredBundleSizeBytes > 0) {
        long tableSizeBytes = (targetTable != null) ? targetTable.getNumBytes() : 0;
        streamCount = (int) Math.min(tableSizeBytes / desiredBundleSizeBytes, MAX_SPLIT_COUNT);
    }
    streamCount = Math.max(streamCount, MIN_SPLIT_COUNT);
    CreateReadSessionRequest createReadSessionRequest = CreateReadSessionRequest.newBuilder().setParent(BigQueryHelpers.toProjectResourceName(bqOptions.getBigQueryProject() == null ? bqOptions.getProject() : bqOptions.getBigQueryProject())).setReadSession(readSessionBuilder).setMaxStreamCount(streamCount).build();
    ReadSession readSession;
    try (StorageClient client = bqServices.getStorageClient(bqOptions)) {
        readSession = client.createReadSession(createReadSessionRequest);
        LOG.info("Sent BigQuery Storage API CreateReadSession request '{}'; received response '{}'.", createReadSessionRequest, readSession);
    }
    if (readSession.getStreamsList().isEmpty()) {
        // The underlying table is empty or all rows have been pruned.
        return ImmutableList.of();
    }
    Schema sessionSchema;
    if (readSession.getDataFormat() == DataFormat.ARROW) {
        org.apache.arrow.vector.types.pojo.Schema schema = ArrowConversion.arrowSchemaFromInput(readSession.getArrowSchema().getSerializedSchema().newInput());
        org.apache.beam.sdk.schemas.Schema beamSchema = ArrowConversion.ArrowSchemaTranslator.toBeamSchema(schema);
        sessionSchema = AvroUtils.toAvroSchema(beamSchema);
    } else if (readSession.getDataFormat() == DataFormat.AVRO) {
        sessionSchema = new Schema.Parser().parse(readSession.getAvroSchema().getSchema());
    } else {
        throw new IllegalArgumentException("data is not in a supported dataFormat: " + readSession.getDataFormat());
    }
    TableSchema trimmedSchema = BigQueryAvroUtils.trimBigQueryTableSchema(targetTable.getSchema(), sessionSchema);
    List<BigQueryStorageStreamSource<T>> sources = Lists.newArrayList();
    for (ReadStream readStream : readSession.getStreamsList()) {
        sources.add(BigQueryStorageStreamSource.create(readSession, readStream, trimmedSchema, parseFn, outputCoder, bqServices));
    }
    return ImmutableList.copyOf(sources);
}
Also used : TableSchema(com.google.api.services.bigquery.model.TableSchema) Schema(org.apache.avro.Schema) TableSchema(com.google.api.services.bigquery.model.TableSchema) ReadStream(com.google.cloud.bigquery.storage.v1.ReadStream) Table(com.google.api.services.bigquery.model.Table) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) Nullable(org.checkerframework.checker.nullness.qual.Nullable) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest)

Example 3 with ReadStream

use of com.google.cloud.bigquery.storage.v1beta2.ReadStream in project beam by apache.

the class BigQueryIOStorageReadTest method testStreamSourceSplitAtFractionRepeatedArrow.

@Test
public void testStreamSourceSplitAtFractionRepeatedArrow() throws Exception {
    List<ReadStream> readStreams = Lists.newArrayList(ReadStream.newBuilder().setName("stream1").build(), ReadStream.newBuilder().setName("stream2").build(), ReadStream.newBuilder().setName("stream3").build());
    StorageClient fakeStorageClient = mock(StorageClient.class);
    List<String> names = Arrays.asList("A", "B", "C", "D", "E", "F");
    List<Long> values = Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L);
    List<ReadRowsResponse> parentResponses = Lists.newArrayList(createResponseArrow(ARROW_SCHEMA, names.subList(0, 2), values.subList(0, 2), 0.0, 0.25), createResponseArrow(ARROW_SCHEMA, names.subList(2, 4), values.subList(2, 4), 0.25, 0.5), createResponseArrow(ARROW_SCHEMA, names.subList(4, 6), values.subList(4, 6), 0.5, 0.75));
    // Mock the initial ReadRows call.
    when(fakeStorageClient.readRows(ReadRowsRequest.newBuilder().setReadStream(readStreams.get(0).getName()).build(), "")).thenReturn(new FakeBigQueryServerStream<>(parentResponses));
    // Mock the first SplitReadStream call.
    when(fakeStorageClient.splitReadStream(SplitReadStreamRequest.newBuilder().setName(readStreams.get(0).getName()).setFraction(0.83f).build())).thenReturn(SplitReadStreamResponse.newBuilder().setPrimaryStream(readStreams.get(1)).setRemainderStream(ReadStream.newBuilder().setName("ignored")).build());
    List<ReadRowsResponse> otherResponses = Lists.newArrayList(createResponseArrow(ARROW_SCHEMA, names.subList(1, 3), values.subList(1, 3), 0.0, 0.50), createResponseArrow(ARROW_SCHEMA, names.subList(3, 4), values.subList(3, 4), 0.5, 0.75));
    // Mock the second ReadRows call.
    when(fakeStorageClient.readRows(ReadRowsRequest.newBuilder().setReadStream(readStreams.get(1).getName()).setOffset(1).build(), "")).thenReturn(new FakeBigQueryServerStream<>(otherResponses));
    // Mock the second SplitReadStream call.
    when(fakeStorageClient.splitReadStream(SplitReadStreamRequest.newBuilder().setName(readStreams.get(1).getName()).setFraction(0.75f).build())).thenReturn(SplitReadStreamResponse.newBuilder().setPrimaryStream(readStreams.get(2)).setRemainderStream(ReadStream.newBuilder().setName("ignored")).build());
    List<ReadRowsResponse> lastResponses = Lists.newArrayList(createResponseArrow(ARROW_SCHEMA, names.subList(2, 4), values.subList(2, 4), 0.80, 0.90));
    // Mock the third ReadRows call.
    when(fakeStorageClient.readRows(ReadRowsRequest.newBuilder().setReadStream(readStreams.get(2).getName()).setOffset(2).build(), "")).thenReturn(new FakeBigQueryServerStream<>(lastResponses));
    BoundedSource<TableRow> source = BigQueryStorageStreamSource.create(ReadSession.newBuilder().setName("readSession").setArrowSchema(ArrowSchema.newBuilder().setSerializedSchema(serializeArrowSchema(ARROW_SCHEMA)).build()).setDataFormat(DataFormat.ARROW).build(), readStreams.get(0), TABLE_SCHEMA, new TableRowParser(), TableRowJsonCoder.of(), new FakeBigQueryServices().withStorageClient(fakeStorageClient));
    BoundedReader<TableRow> reader = source.createReader(options);
    assertTrue(reader.start());
    assertEquals("A", reader.getCurrent().get("name"));
    BoundedSource<TableRow> residualSource = reader.splitAtFraction(0.83f);
    assertNotNull(residualSource);
    assertEquals("A", reader.getCurrent().get("name"));
    assertTrue(reader.advance());
    assertEquals("B", reader.getCurrent().get("name"));
    residualSource = reader.splitAtFraction(0.75f);
    assertNotNull(residualSource);
    assertEquals("B", reader.getCurrent().get("name"));
    assertTrue(reader.advance());
    assertEquals("C", reader.getCurrent().get("name"));
    assertTrue(reader.advance());
    assertEquals("D", reader.getCurrent().get("name"));
    assertFalse(reader.advance());
}
Also used : StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) ByteString(com.google.protobuf.ByteString) TableRowParser(org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser) ReadRowsResponse(com.google.cloud.bigquery.storage.v1.ReadRowsResponse) ReadStream(com.google.cloud.bigquery.storage.v1.ReadStream) TableRow(com.google.api.services.bigquery.model.TableRow) FakeBigQueryServices(org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices) Test(org.junit.Test)

Example 4 with ReadStream

use of com.google.cloud.bigquery.storage.v1beta2.ReadStream in project beam by apache.

the class BigQueryIOStorageReadTest method testStreamSourceSplitAtFractionRepeated.

@Test
public void testStreamSourceSplitAtFractionRepeated() throws Exception {
    List<ReadStream> readStreams = Lists.newArrayList(ReadStream.newBuilder().setName("stream1").build(), ReadStream.newBuilder().setName("stream2").build(), ReadStream.newBuilder().setName("stream3").build());
    StorageClient fakeStorageClient = mock(StorageClient.class);
    // Mock the initial ReadRows call.
    when(fakeStorageClient.readRows(ReadRowsRequest.newBuilder().setReadStream(readStreams.get(0).getName()).build(), "")).thenReturn(new FakeBigQueryServerStream<>(Lists.newArrayList(createResponse(AVRO_SCHEMA, Lists.newArrayList(createRecord("A", 1, AVRO_SCHEMA), createRecord("B", 2, AVRO_SCHEMA)), 0.0, 0.25), createResponse(AVRO_SCHEMA, Lists.newArrayList(createRecord("C", 3, AVRO_SCHEMA), createRecord("D", 4, AVRO_SCHEMA)), 0.25, 0.50), createResponse(AVRO_SCHEMA, Lists.newArrayList(createRecord("E", 5, AVRO_SCHEMA), createRecord("F", 6, AVRO_SCHEMA)), 0.5, 0.75))));
    // Mock the first SplitReadStream call.
    when(fakeStorageClient.splitReadStream(SplitReadStreamRequest.newBuilder().setName(readStreams.get(0).getName()).setFraction(0.83f).build())).thenReturn(SplitReadStreamResponse.newBuilder().setPrimaryStream(readStreams.get(1)).setRemainderStream(ReadStream.newBuilder().setName("ignored")).build());
    // Mock the second ReadRows call.
    when(fakeStorageClient.readRows(ReadRowsRequest.newBuilder().setReadStream(readStreams.get(1).getName()).setOffset(1).build(), "")).thenReturn(new FakeBigQueryServerStream<>(Lists.newArrayList(createResponse(AVRO_SCHEMA, Lists.newArrayList(createRecord("B", 2, AVRO_SCHEMA), createRecord("C", 3, AVRO_SCHEMA)), 0.0, 0.50), createResponse(AVRO_SCHEMA, Lists.newArrayList(createRecord("D", 4, AVRO_SCHEMA), createRecord("E", 5, AVRO_SCHEMA)), 0.5, 0.75))));
    // Mock the second SplitReadStream call.
    when(fakeStorageClient.splitReadStream(SplitReadStreamRequest.newBuilder().setName(readStreams.get(1).getName()).setFraction(0.75f).build())).thenReturn(SplitReadStreamResponse.newBuilder().setPrimaryStream(readStreams.get(2)).setRemainderStream(ReadStream.newBuilder().setName("ignored")).build());
    // Mock the third ReadRows call.
    when(fakeStorageClient.readRows(ReadRowsRequest.newBuilder().setReadStream(readStreams.get(2).getName()).setOffset(2).build(), "")).thenReturn(new FakeBigQueryServerStream<>(Lists.newArrayList(createResponse(AVRO_SCHEMA, Lists.newArrayList(createRecord("C", 3, AVRO_SCHEMA), createRecord("D", 4, AVRO_SCHEMA)), 0.80, 0.90))));
    BoundedSource<TableRow> source = BigQueryStorageStreamSource.create(ReadSession.newBuilder().setName("readSession").setAvroSchema(AvroSchema.newBuilder().setSchema(AVRO_SCHEMA_STRING)).build(), readStreams.get(0), TABLE_SCHEMA, new TableRowParser(), TableRowJsonCoder.of(), new FakeBigQueryServices().withStorageClient(fakeStorageClient));
    BoundedReader<TableRow> reader = source.createReader(options);
    assertTrue(reader.start());
    assertEquals("A", reader.getCurrent().get("name"));
    BoundedSource<TableRow> residualSource = reader.splitAtFraction(0.83f);
    assertNotNull(residualSource);
    assertEquals("A", reader.getCurrent().get("name"));
    assertTrue(reader.advance());
    assertEquals("B", reader.getCurrent().get("name"));
    residualSource = reader.splitAtFraction(0.75f);
    assertNotNull(residualSource);
    assertEquals("B", reader.getCurrent().get("name"));
    assertTrue(reader.advance());
    assertEquals("C", reader.getCurrent().get("name"));
    assertTrue(reader.advance());
    assertEquals("D", reader.getCurrent().get("name"));
    assertFalse(reader.advance());
}
Also used : ReadStream(com.google.cloud.bigquery.storage.v1.ReadStream) TableRow(com.google.api.services.bigquery.model.TableRow) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) FakeBigQueryServices(org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices) TableRowParser(org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser) Test(org.junit.Test)

Example 5 with ReadStream

use of com.google.cloud.bigquery.storage.v1beta2.ReadStream in project spark-bigquery-connector by GoogleCloudDataproc.

the class BigQueryDataSourceReaderContext method planBatchInputPartitionContexts.

public Stream<InputPartitionContext<ColumnarBatch>> planBatchInputPartitionContexts() {
    if (!enableBatchRead()) {
        throw new IllegalStateException("Batch reads should not be enabled");
    }
    ImmutableList<String> selectedFields = schema.map(requiredSchema -> ImmutableList.copyOf(requiredSchema.fieldNames())).orElse(ImmutableList.copyOf(fields.keySet()));
    Optional<String> filter = getCombinedFilter();
    ReadSessionResponse readSessionResponse = readSessionCreator.create(tableId, selectedFields, filter);
    ReadSession readSession = readSessionResponse.getReadSession();
    logger.info("Created read session for {}: {} for application id: {}", tableId.toString(), readSession.getName(), applicationId);
    if (selectedFields.isEmpty()) {
        // means select *
        Schema tableSchema = SchemaConverters.getSchemaWithPseudoColumns(readSessionResponse.getReadTableInfo());
        selectedFields = tableSchema.getFields().stream().map(Field::getName).collect(ImmutableList.toImmutableList());
    }
    ImmutableList<String> partitionSelectedFields = selectedFields;
    return Streams.stream(Iterables.partition(readSession.getStreamsList(), readSessionCreatorConfig.streamsPerPartition())).map(streams -> new ArrowInputPartitionContext(bigQueryReadClientFactory, bigQueryTracerFactory, streams.stream().map(ReadStream::getName).collect(Collectors.toCollection(ArrayList::new)), readSessionCreatorConfig.toReadRowsHelperOptions(), partitionSelectedFields, readSessionResponse, userProvidedSchema));
}
Also used : IntStream(java.util.stream.IntStream) Iterables(com.google.common.collect.Iterables) InternalRow(org.apache.spark.sql.catalyst.InternalRow) TableId(com.google.cloud.bigquery.TableId) LoggerFactory(org.slf4j.LoggerFactory) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) OptionalLong(java.util.OptionalLong) ImmutableList(com.google.common.collect.ImmutableList) Schema(com.google.cloud.bigquery.Schema) Map(java.util.Map) ReadSessionResponse(com.google.cloud.bigquery.connector.common.ReadSessionResponse) StructField(org.apache.spark.sql.types.StructField) StructType(org.apache.spark.sql.types.StructType) Field(com.google.cloud.bigquery.Field) TableDefinition(com.google.cloud.bigquery.TableDefinition) ReadSessionCreator(com.google.cloud.bigquery.connector.common.ReadSessionCreator) JavaConversions(scala.collection.JavaConversions) ReadStream(com.google.cloud.bigquery.storage.v1.ReadStream) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) ReadSessionCreatorConfig(com.google.cloud.bigquery.connector.common.ReadSessionCreatorConfig) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) BigQueryClient(com.google.cloud.bigquery.connector.common.BigQueryClient) Set(java.util.Set) SchemaConverters(com.google.cloud.spark.bigquery.SchemaConverters) Streams(com.google.common.collect.Streams) Collectors(java.util.stream.Collectors) DataFormat(com.google.cloud.bigquery.storage.v1.DataFormat) List(java.util.List) Stream(java.util.stream.Stream) ColumnarBatch(org.apache.spark.sql.vectorized.ColumnarBatch) ReadRowsResponseToInternalRowIteratorConverter(com.google.cloud.spark.bigquery.ReadRowsResponseToInternalRowIteratorConverter) BigQueryClientFactory(com.google.cloud.bigquery.connector.common.BigQueryClientFactory) SparkFilterUtils(com.google.cloud.spark.bigquery.SparkFilterUtils) Optional(java.util.Optional) Filter(org.apache.spark.sql.sources.Filter) TableInfo(com.google.cloud.bigquery.TableInfo) BigQueryUtil(com.google.cloud.bigquery.connector.common.BigQueryUtil) BigQueryTracerFactory(com.google.cloud.bigquery.connector.common.BigQueryTracerFactory) StructField(org.apache.spark.sql.types.StructField) Field(com.google.cloud.bigquery.Field) ReadSessionResponse(com.google.cloud.bigquery.connector.common.ReadSessionResponse) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) Schema(com.google.cloud.bigquery.Schema)

Aggregations

ReadStream (com.google.cloud.bigquery.storage.v1.ReadStream)5 Test (org.junit.Test)4 ReadSession (com.google.cloud.bigquery.storage.v1.ReadSession)3 ArrayList (java.util.ArrayList)3 StorageClient (org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient)3 TableRow (com.google.api.services.bigquery.model.TableRow)2 ReadRowsRequest (com.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest)2 ReadRowsResponse (com.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse)2 IOException (java.io.IOException)2 Callable (java.util.concurrent.Callable)2 ExecutionException (java.util.concurrent.ExecutionException)2 ExecutorService (java.util.concurrent.ExecutorService)2 Future (java.util.concurrent.Future)2 TableRowParser (org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser)2 FakeBigQueryServices (org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices)2 Table (com.google.api.services.bigquery.model.Table)1 TableSchema (com.google.api.services.bigquery.model.TableSchema)1 Field (com.google.cloud.bigquery.Field)1 Schema (com.google.cloud.bigquery.Schema)1 TableDefinition (com.google.cloud.bigquery.TableDefinition)1