apache_beam.io.gcp.bigquery module

BigQuery sources and sinks.

This module implements reading from and writing to BigQuery tables. It relies on several classes exposed by the BigQuery API: TableSchema, TableFieldSchema, TableRow, and TableCell. The default mode is to return table rows read from a BigQuery source as dictionaries. Similarly a Write transform to a BigQuerySink accepts PCollections of dictionaries. This is done for more convenient programming. If desired, the native TableRow objects can be used throughout to represent rows (use an instance of TableRowJsonCoder as a coder argument when creating the sources or sinks respectively).

Also, for programming convenience, instances of TableReference and TableSchema have a string representation that can be used for the corresponding arguments:

  • TableReference can be a PROJECT:DATASET.TABLE or DATASET.TABLE string.
  • TableSchema can be a NAME:TYPE{,NAME:TYPE}* string (e.g. ‘month:STRING,event_count:INTEGER’).

The syntax supported is described here: https://cloud.google.com/bigquery/bq-command-line-tool-quickstart

BigQuery sources can be used as main inputs or side inputs. A main input (common case) is expected to be massive and will be split into manageable chunks and processed in parallel. Side inputs are expected to be small and will be read completely every time a ParDo DoFn gets executed. In the example below the lambda function implementing the DoFn for the Map transform will get on each call one row of the main table and all rows of the side table. The runner may use some caching techniques to share the side inputs between calls in order to avoid excessive reading::

main_table = pipeline | 'VeryBig' >> beam.io.Read(beam.io.BigQuerySource()
side_table = pipeline | 'NotBig' >> beam.io.Read(beam.io.BigQuerySource()
results = (
    main_table
    | 'ProcessData' >> beam.Map(
        lambda element, side_input: ..., AsList(side_table)))

There is no difference in how main and side inputs are read. What makes the side_table a ‘side input’ is the AsList wrapper used when passing the table as a parameter to the Map transform. AsList signals to the execution framework that its input should be made available whole.

The main and side inputs are implemented differently. Reading a BigQuery table as main input entails exporting the table to a set of GCS files (currently in JSON format) and then processing those files. Reading the same table as a side input entails querying the table for all its rows. The coder argument on BigQuerySource controls the reading of the lines in the export files (i.e., transform a JSON object into a PCollection element). The coder is not involved when the same table is read as a side input since there is no intermediate format involved. We get the table rows directly from the BigQuery service with a query.

Users may provide a query to read from rather than reading all of a BigQuery table. If specified, the result obtained by executing the specified query will be used as the data of the input transform.:

query_results = pipeline | beam.io.Read(beam.io.BigQuerySource(
    query='SELECT year, mean_temp FROM samples.weather_stations'))

When creating a BigQuery input transform, users should provide either a query or a table. Pipeline construction will fail with a validation error if neither or both are specified.

Writing Data to BigQuery

The WriteToBigQuery transform is the recommended way of writing data to BigQuery. It supports a large set of parameters to customize how you’d like to write to BigQuery.

Table References

This transform allows you to provide static project, dataset and table parameters which point to a specific BigQuery table to be created. The table parameter can also be a dynamic parameter (i.e. a callable), which receives an element to be written to BigQuery, and returns the table that that element should be sent to.

You may also provide a tuple of PCollectionView elements to be passed as side inputs to your callable. For example, suppose that one wishes to send events of different types to different tables, and the table names are computed at pipeline runtime, one may do something like the following:

with Pipeline() as p:
  elements = (p | beam.Create([
    {'type': 'error', 'timestamp': '12:34:56', 'message': 'bad'},
    {'type': 'user_log', 'timestamp': '12:34:59', 'query': 'flu symptom'},
  ]))

  table_names = (p | beam.Create([
    ('error', 'my_project.dataset1.error_table_for_today'),
    ('user_log', 'my_project.dataset1.query_table_for_today'),
  ])

  table_names_dict = beam.pvalue.AsDict(table_names)

  elements | beam.io.gcp.WriteToBigQuery(
    table=lambda row, table_dict: table_dict[row['type']],
    table_side_inputs=(table_names_dict,))

In the example above, the table_dict argument passed to the function in table_dict is the side input coming from table_names_dict, which is passed as part of the table_side_inputs argument.

Schemas

This transform also allows you to provide a static or dynamic schema parameter (i.e. a callable).

If providing a callable, this should take in a table reference (as returned by the table parameter), and return the corresponding schema for that table. This allows to provide different schemas for different tables:

def compute_table_name(row):
  ...

errors_schema = {'fields': [
  {'name': 'type', 'type': 'STRING', 'mode': 'NULLABLE'},
  {'name': 'message', 'type': 'STRING', 'mode': 'NULLABLE'}]}
queries_schema = {'fields': [
  {'name': 'type', 'type': 'STRING', 'mode': 'NULLABLE'},
  {'name': 'query', 'type': 'STRING', 'mode': 'NULLABLE'}]}

with Pipeline() as p:
  elements = (p | beam.Create([
    {'type': 'error', 'timestamp': '12:34:56', 'message': 'bad'},
    {'type': 'user_log', 'timestamp': '12:34:59', 'query': 'flu symptom'},
  ]))

  elements | beam.io.gcp.WriteToBigQuery(
    table=compute_table_name,
    schema=lambda table: (errors_schema
                          if 'errors' in table
                          else queries_schema))

It may be the case that schemas are computed at pipeline runtime. In cases like these, one can also provide a schema_side_inputs parameter, which is a tuple of PCollectionViews to be passed to the schema callable (much like the table_side_inputs parameter).

Additional Parameters for BigQuery Tables

This sink is able to create tables in BigQuery if they don’t already exist. It also relies on creating temporary tables when performing file loads.

The WriteToBigQuery transform creates tables using the BigQuery API by inserting a load job (see the API reference [1]), or by inserting a new table (see the API reference for that [2][3]).

When creating a new BigQuery table, there are a number of extra parameters that one may need to specify. For example, clustering, partitioning, data encoding, etc. It is possible to provide these additional parameters by passing a Python dictionary as additional_bq_parameters to the transform. As an example, to create a table that has specific partitioning, and clustering properties, one would do the following:

additional_bq_parameters = {
  'timePartitioning': {'type': 'DAY'},
  'clustering': {'fields': ['country']}}
with Pipeline() as p:
  elements = (p | beam.Create([
    {'country': 'mexico', 'timestamp': '12:34:56', 'query': 'acapulco'},
    {'country': 'canada', 'timestamp': '12:34:59', 'query': 'influenza'},
  ]))

  elements | beam.io.gcp.WriteToBigQuery(
    table='project_name1.dataset_2.query_events_table',
    additional_bq_parameters=additional_bq_parameters)

Much like the schema case, the parameter with additional_bq_parameters can also take a callable that receives a table reference.

[1] https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load [2] https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert [3] https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#resource

* Short introduction to BigQuery concepts * Tables have rows (TableRow) and each row has cells (TableCell). A table has a schema (TableSchema), which in turn describes the schema of each cell (TableFieldSchema). The terms field and cell are used interchangeably.

TableSchema: Describes the schema (types and order) for values in each row.
Has one attribute, ‘field’, which is list of TableFieldSchema objects.
TableFieldSchema: Describes the schema (type, name) for one field.
Has several attributes, including ‘name’ and ‘type’. Common values for the type attribute are: ‘STRING’, ‘INTEGER’, ‘FLOAT’, ‘BOOLEAN’, ‘NUMERIC’, ‘GEOGRAPHY’. All possible values are described at: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types
TableRow: Holds all values in a table row. Has one attribute, ‘f’, which is a
list of TableCell instances.
TableCell: Holds the value for one cell (or field). Has one attribute,
‘v’, which is a JsonValue instance. This class is defined in apitools.base.py.extra_types.py module.

As of Beam 2.7.0, the NUMERIC data type is supported. This data type supports high-precision decimal numbers (precision of 38 digits, scale of 9 digits). The GEOGRAPHY data type works with Well-Known Text (See https://en.wikipedia.org/wiki/Well-known_text) format for reading and writing to BigQuery.

class apache_beam.io.gcp.bigquery.TableRowJsonCoder(table_schema=None)[source]

Bases: apache_beam.coders.coders.Coder

A coder for a TableRow instance to/from a JSON string.

Note that the encoding operation (used when writing to sinks) requires the table schema in order to obtain the ordered list of field names. Reading from sources on the other hand does not need the table schema.

encode(table_row)[source]
decode(encoded_table_row)[source]
class apache_beam.io.gcp.bigquery.BigQueryDisposition[source]

Bases: future.types.newobject.newobject

Class holding standard strings used for create and write dispositions.

CREATE_NEVER = 'CREATE_NEVER'
CREATE_IF_NEEDED = 'CREATE_IF_NEEDED'
WRITE_TRUNCATE = 'WRITE_TRUNCATE'
WRITE_APPEND = 'WRITE_APPEND'
WRITE_EMPTY = 'WRITE_EMPTY'
static validate_create(disposition)[source]
static validate_write(disposition)[source]
class apache_beam.io.gcp.bigquery.BigQuerySource(table=None, dataset=None, project=None, query=None, validate=False, coder=None, use_standard_sql=False, flatten_results=True, kms_key=None)[source]

Bases: apache_beam.runners.dataflow.native_io.iobase.NativeSource

A source based on a BigQuery table.

Initialize a BigQuerySource.

Parameters:
  • table (str) – The ID of a BigQuery table. If specified all data of the table will be used as input of the current source. The ID must contain only letters a-z, A-Z, numbers 0-9, or underscores _. If dataset and query arguments are None then the table argument must contain the entire table reference specified as: 'DATASET.TABLE' or 'PROJECT:DATASET.TABLE'.
  • dataset (str) – The ID of the dataset containing this table or None if the table reference is specified entirely by the table argument or a query is specified.
  • project (str) – The ID of the project containing this table or None if the table reference is specified entirely by the table argument or a query is specified.
  • query (str) – A query to be used instead of arguments table, dataset, and project.
  • validate (bool) – If True, various checks will be done when source gets initialized (e.g., is table present?). This should be True for most scenarios in order to catch errors as early as possible (pipeline construction instead of pipeline execution). It should be False if the table is created during pipeline execution by a previous step.
  • coder (Coder) – The coder for the table rows if serialized to disk. If None, then the default coder is RowAsDictJsonCoder, which will interpret every line in a file as a JSON serialized dictionary. This argument needs a value only in special cases when returning table rows as dictionaries is not desirable.
  • use_standard_sql (bool) – Specifies whether to use BigQuery’s standard SQL dialect for this query. The default value is False. If set to True, the query will use BigQuery’s updated SQL dialect with improved standards compliance. This parameter is ignored for table inputs.
  • flatten_results (bool) – Flattens all nested and repeated fields in the query results. The default value is True.
  • kms_key (str) – Experimental. Optional Cloud KMS key name for use when creating new tables.
Raises:

ValueError – if any of the following is true:

  1. the table reference as a string does not match the expected format
  2. neither a table nor a query is specified
  3. both a table and a query is specified.
display_data()[source]
format

Source format name required for remote execution.

reader(test_bigquery_client=None)[source]
class apache_beam.io.gcp.bigquery.BigQuerySink(table, dataset=None, project=None, schema=None, create_disposition='CREATE_IF_NEEDED', write_disposition='WRITE_EMPTY', validate=False, coder=None, kms_key=None)[source]

Bases: apache_beam.runners.dataflow.native_io.iobase.NativeSink

A sink based on a BigQuery table.

This BigQuery sink triggers a Dataflow native sink for BigQuery that only supports batch pipelines. Instead of using this sink directly, please use WriteToBigQuery transform that works for both batch and streaming pipelines.

Initialize a BigQuerySink.

Parameters:
  • table (str) – The ID of the table. The ID must contain only letters a-z, A-Z, numbers 0-9, or underscores _. If dataset argument is None then the table argument must contain the entire table reference specified as: 'DATASET.TABLE' or 'PROJECT:DATASET.TABLE'.
  • dataset (str) – The ID of the dataset containing this table or None if the table reference is specified entirely by the table argument.
  • project (str) – The ID of the project containing this table or None if the table reference is specified entirely by the table argument.
  • schema (str) – The schema to be used if the BigQuery table to write has to be created. This can be either specified as a TableSchema object or a single string of the form 'field1:type1,field2:type2,field3:type3' that defines a comma separated list of fields. Here 'type' should specify the BigQuery type of the field. Single string based schemas do not support nested fields, repeated fields, or specifying a BigQuery mode for fields (mode will always be set to 'NULLABLE').
  • create_disposition (BigQueryDisposition) –

    A string describing what happens if the table does not exist. Possible values are:

  • write_disposition (BigQueryDisposition) –

    A string describing what happens if the table has already some data. Possible values are:

  • validate (bool) – If True, various checks will be done when sink gets initialized (e.g., is table present given the disposition arguments?). This should be True for most scenarios in order to catch errors as early as possible (pipeline construction instead of pipeline execution). It should be False if the table is created during pipeline execution by a previous step.
  • coder (Coder) – The coder for the table rows if serialized to disk. If None, then the default coder is RowAsDictJsonCoder, which will interpret every element written to the sink as a dictionary that will be JSON serialized as a line in a file. This argument needs a value only in special cases when writing table rows as dictionaries is not desirable.
  • kms_key (str) – Experimental. Optional Cloud KMS key name for use when creating new tables.
Raises:
  • TypeError – if the schema argument is not a str or a TableSchema object.
  • ValueError – if the table reference as a string does not match the expected format.
display_data()[source]
schema_as_json()[source]

Returns the TableSchema associated with the sink as a JSON string.

format

Sink format name required for remote execution.

writer(test_bigquery_client=None, buffer_size=None)[source]
class apache_beam.io.gcp.bigquery.WriteToBigQuery(table, dataset=None, project=None, schema=None, create_disposition='CREATE_IF_NEEDED', write_disposition='WRITE_APPEND', kms_key=None, batch_size=None, max_file_size=None, max_files_per_bundle=None, test_client=None, custom_gcs_temp_location=None, method=None, insert_retry_strategy=None, additional_bq_parameters=None, table_side_inputs=None, schema_side_inputs=None, validate=True)[source]

Bases: apache_beam.transforms.ptransform.PTransform

Write data to BigQuery.

This transform receives a PCollection of elements to be inserted into BigQuery tables. The elements would come in as Python dictionaries, or as TableRow instances.

Initialize a WriteToBigQuery transform.

Parameters:
  • table (str, callable, ValueProvider) – The ID of the table, or a callable that returns it. The ID must contain only letters a-z, A-Z, numbers 0-9, or underscores _. If dataset argument is None then the table argument must contain the entire table reference specified as: 'DATASET.TABLE' or 'PROJECT:DATASET.TABLE'. If it’s a callable, it must receive one argument representing an element to be written to BigQuery, and return a TableReference, or a string table name as specified above. Multiple destinations are only supported on Batch pipelines at the moment.
  • dataset (str) – The ID of the dataset containing this table or None if the table reference is specified entirely by the table argument.
  • project (str) – The ID of the project containing this table or None if the table reference is specified entirely by the table argument.
  • schema (str,dict,ValueProvider,callable) – The schema to be used if the BigQuery table to write has to be created. This can be either specified as a TableSchema. or a ValueProvider that has a JSON string, or a python dictionary, or the string or dictionary itself, object or a single string of the form 'field1:type1,field2:type2,field3:type3' that defines a comma separated list of fields. Here 'type' should specify the BigQuery type of the field. Single string based schemas do not support nested fields, repeated fields, or specifying a BigQuery mode for fields (mode will always be set to 'NULLABLE'). If a callable, then it should receive a destination (in the form of a TableReference or a string, and return a str, dict or TableSchema. One may also pass SCHEMA_AUTODETECT here, and BigQuery will try to infer the schema for the files that are being loaded.
  • create_disposition (BigQueryDisposition) –

    A string describing what happens if the table does not exist. Possible values are:

  • write_disposition (BigQueryDisposition) –

    A string describing what happens if the table has already some data. Possible values are:

    For streaming pipelines WriteTruncate can not be used.

  • kms_key (str) – Experimental. Optional Cloud KMS key name for use when creating new tables.
  • batch_size (int) – Number of rows to be written to BQ per streaming API insert. The default is 500. insert.
  • test_client – Override the default bigquery client used for testing.
  • max_file_size (int) – The maximum size for a file to be written and then loaded into BigQuery. The default value is 4TB, which is 80% of the limit of 5TB for BigQuery to load any file.
  • max_files_per_bundle (int) – The maximum number of files to be concurrently written by a worker. The default here is 20. Larger values will allow writing to multiple destinations without having to reshard - but they increase the memory burden on the workers.
  • custom_gcs_temp_location (str) – A GCS location to store files to be used for file loads into BigQuery. By default, this will use the pipeline’s temp_location, but for pipelines whose temp_location is not appropriate for BQ File Loads, users should pass a specific one.
  • method – The method to use to write to BigQuery. It may be STREAMING_INSERTS, FILE_LOADS, or DEFAULT. An introduction on loading data to BigQuery: https://cloud.google.com/bigquery/docs/loading-data. DEFAULT will use STREAMING_INSERTS on Streaming pipelines and FILE_LOADS on Batch pipelines.
  • insert_retry_strategy – The strategy to use when retrying streaming inserts into BigQuery. Options are shown in bigquery_tools.RetryStrategy attrs.
  • additional_bq_parameters (callable) – A function that returns a dictionary with additional parameters to pass to BQ when creating / loading data into a table. These can be ‘timePartitioning’, ‘clustering’, etc. They are passed directly to the job load configuration. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load
  • table_side_inputs (tuple) – A tuple with AsSideInput PCollections to be passed to the table callable (if one is provided).
  • schema_side_inputs – A tuple with AsSideInput PCollections to be passed to the schema callable (if one is provided).
  • validate – Indicates whether to perform validation checks on inputs. This parameter is primarily used for testing.
class Method[source]

Bases: future.types.newobject.newobject

DEFAULT = 'DEFAULT'
STREAMING_INSERTS = 'STREAMING_INSERTS'
FILE_LOADS = 'FILE_LOADS'
static get_table_schema_from_string(schema)[source]

Transform the string table schema into a TableSchema instance.

Parameters:schema (str) – The sting schema to be used if the BigQuery table to write has to be created.
Returns:The schema to be used if the BigQuery table to write has to be created but in the TableSchema format.
Return type:TableSchema
static table_schema_to_dict(table_schema)[source]

Create a dictionary representation of table schema for serialization

static get_dict_table_schema(schema)[source]

Transform the table schema into a dictionary instance.

Parameters:schema (TableSchema) – The schema to be used if the BigQuery table to write has to be created. This can either be a dict or string or in the TableSchema format.
Returns:The schema to be used if the BigQuery table to write has to be created but in the dictionary format.
Return type:Dict[str, Any]
expand(pcoll)[source]
display_data()[source]