Skip to content

spark.GBQQueryDataset

spark.GBQQueryDataset loads and saves data to/from Google BigQuery tables using Spark.

kedro_datasets.spark.GBQQueryDataset

GBQQueryDataset(
    materialization_dataset,
    sql=None,
    filepath=None,
    materialization_project=None,
    load_args=None,
    fs_args=None,
    bq_credentials=None,
    fs_credentials=None,
    metadata=None,
)

Bases: AbstractDataset[None, DataFrame]

GBQQueryDataset loads data from Google BigQuery with a SQL query using BigQuery Spark connector.

Examples:

Using the YAML API:

my_gbq_spark_data:
  type: spark.GBQQueryDataset
  sql: |
    SELECT * FROM your_table
  materialization_dataset: your_dataset
  materialization_project: your_project
  bq_credentials:
    file: /path/to/your/credentials.json
  fs_credentials:
    key: value

Using the Python API:

>>> from kedro_datasets.spark import GBQQueryDataset
>>>
>>> # Define your SQL query
>>> sql = "SELECT * FROM your_table"
>>>
>>> # Initialize dataset
>>> dataset = GBQQueryDataset(
...     sql=sql,
...     materialization_dataset="your_dataset",
...     materialization_project="your_project",  # optional
...     bq_credentials=dict(file="/path/to/your/credentials.json"),  # optional
...     fs_credentials=dict(key="value"),  # optional
... )
>>>
>>> # Load data
>>> df = dataset.load()
>>>
>>> # Example output
>>> df.show()

Parameters:

  • materialization_dataset (str) –

    The name of the dataset to materialize the query results.

  • sql (str | None, default: None ) –

    The SQL query to execute

  • filepath (str | PathLike | None, default: None ) –

    A path to a file with a sql query statement.

  • materialization_project (str | None, default: None ) –

    The name of the project to materialize the query results. Optional (defaults to the project id set by the credentials).

  • load_args (dict[str, Any] | None, default: None ) –

    Load args passed to Spark DataFrameReader load method. It is dependent on the selected file format. You can find a list of read options for each supported format in Spark DataFrame read documentation: https://spark.apache.org/docs/latest/api/python/getting_started/quickstart_df.html

  • bq_credentials (dict[str, Any] | None, default: None ) –

    Credentials to authenticate spark session with google bigquery. Dictionary with key specifying the type of credentials ('base64', 'file', 'json'). Alternatively, you can pass the credentials in load_args as follows:

    When passing as base64: load_args={"credentials": "your_credentials"}

    When passing as a file: load_args={"credentialsFile": "/path/to/your/credentials.json"}

    When passing as a json object: This is not supported when passed directly in load_args. You can pass the json object (as a python dictionary) in the credentials by specifying the key as json.

    Read more here: https://github.com/GoogleCloudDataproc/spark-bigquery-connector?tab=readme-ov-file#how-do-i-authenticate-outside-gce--dataproc

  • fs_credentials (dict[str, Any] | None, default: None ) –

    Credentials to authenticate with the filesystem. The keyword args would be directly passed to fsspec.filesystem constructor.

  • metadata (dict[str, Any] | None, default: None ) –

    Any arbitrary metadata. This is ignored by Kedro, but may be consumed by users or external plugins.

Source code in kedro_datasets/spark/gbq_dataset.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def __init__(  # noqa: PLR0913
    self,
    materialization_dataset: str,
    sql: str | None = None,
    filepath: str | os.PathLike | None = None,
    materialization_project: str | None = None,
    load_args: dict[str, Any] | None = None,
    fs_args: dict[str, Any] | None = None,
    bq_credentials: dict[str, Any] | None = None,
    fs_credentials: dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Creates a new instance of ``SparkGBQDataSet`` pointing to a specific table in Google BigQuery.

    Args:
        materialization_dataset: The name of the dataset to materialize the query results.
        sql: The SQL query to execute
        filepath: A path to a file with a sql query statement.
        materialization_project: The name of the project to materialize the query results.
            Optional (defaults to the project id set by the credentials).
        load_args: Load args passed to Spark DataFrameReader load method.
            It is dependent on the selected file format. You can find
            a list of read options for each supported format
            in Spark DataFrame read documentation:
            https://spark.apache.org/docs/latest/api/python/getting_started/quickstart_df.html
        bq_credentials: Credentials to authenticate spark session with google bigquery.
            Dictionary with key specifying the type of credentials ('base64', 'file', 'json').
            Alternatively, you can pass the credentials in load_args as follows:

            When passing as `base64`:
            `load_args={"credentials": "your_credentials"}`

            When passing as a `file`:
            `load_args={"credentialsFile": "/path/to/your/credentials.json"}`

            When passing as a json object:
            This is not supported when passed directly in load_args. You can pass the json object (as a python dictionary) in the credentials
            by specifying the key as `json`.

            Read more here:
                https://github.com/GoogleCloudDataproc/spark-bigquery-connector?tab=readme-ov-file#how-do-i-authenticate-outside-gce--dataproc
        fs_credentials: Credentials to authenticate with the filesystem.
            The keyword args would be directly passed to fsspec.filesystem constructor.
        metadata: Any arbitrary metadata.
            This is ignored by Kedro, but may be consumed by users or external plugins.
    """
    if sql and filepath:
        raise DatasetError(
            "'sql' and 'filepath' arguments cannot both be provided. "
            "Please only provide one."
        )

    if not (sql or filepath):
        raise DatasetError(
            "'sql' and 'filepath' arguments cannot both be empty. "
            "Please provide a sql query or path to a sql query file."
        )

    if sql:
        self._sql = sql
        self._filepath = None
    else:
        protocol, path = get_protocol_and_path(str(filepath))

        self._fs_args = fs_args or {}
        self._fs_credentials = fs_credentials or {}
        self._fs_protocol = protocol

        self._fs = fsspec.filesystem(
            self._fs_protocol, **self._fs_credentials, **self._fs_args
        )
        self._filepath = path
        self._sql = None  # type: ignore

    self._materialization_dataset = materialization_dataset
    self._materialization_project = materialization_project
    self._load_args = load_args or {}
    self._bq_credentials = bq_credentials or {}

    self._metadata = metadata

load

load()

Loads data from Google BigQuery.

Returns:

  • DataFrame –

    A Spark DataFrame.

Source code in kedro_datasets/spark/gbq_dataset.py
214
215
216
217
218
219
220
221
222
223
def load(self) -> DataFrame:
    """Loads data from Google BigQuery.

    Returns:
        A Spark DataFrame.
    """
    spark = get_spark()
    read_obj = spark.read.format("bigquery")

    return read_obj.load(**self._get_spark_load_args())

save

save(data)
Source code in kedro_datasets/spark/gbq_dataset.py
225
226
def save(self, data: None) -> NoReturn:
    raise DatasetError("'save' is not supported on GBQQueryDataset")