Skip to content

databricks.ExternalTableDataset

kedro_datasets_experimental.databricks.ExternalTableDataset

ExternalTableDataset(
    *,
    table,
    catalog=None,
    database="default",
    format="delta",
    write_mode=None,
    location=None,
    dataframe_type="spark",
    primary_key=None,
    version=None,
    schema=None,
    partition_columns=None,
    owner_group=None,
    metadata=None
)

Bases: BaseTableDataset

ExternalTableDataset loads and saves data into external tables in Databricks. Load and save operations can use either Spark or Pandas DataFrames, specified via the dataframe_type argument.

### Example usage for the [YAML API](https://docs.kedro.org/en/stable/catalog-data/data_catalog_yaml_examples/):

```yaml
names_and_ages@spark:
    type: kedro_datasets_experimental.databricks.ExternalTableDataset
    format: parquet
    table: names_and_ages

names_and_ages@pandas:
    type: kedro_datasets_experimental.databricks.ExternalTableDataset
    format: parquet
    table: names_and_ages
    dataframe_type: pandas
```

### Example usage for the [Python API](https://docs.kedro.org/en/stable/catalog-data/advanced_data_catalog_usage/):
from kedro_datasets_experimental.databricks import ExternalTableDataset
from pyspark.sql import SparkSession
from pyspark.sql.types import IntegerType, Row, StringType, StructField, StructType
import importlib.metadata

DELTA_VERSION = importlib.metadata.version("delta-spark")
major_version = int(DELTA_VERSION.split(".")[0])
delta_package = (
    f"io.delta:delta-spark_2.13:{DELTA_VERSION}"
    if major_version >= 4
    else f"io.delta:delta-core_2.12:{DELTA_VERSION}"
)

schema = StructType(
    [StructField("name", StringType(), True), StructField("age", IntegerType(), True)]
)
data = [("Alex", 31), ("Bob", 12), ("Clarke", 65), ("Dave", 29)]

spark_df = (
    SparkSession.builder.config("spark.jars.packages", delta_package)
    .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
    .config(
        "spark.sql.catalog.spark_catalog",
        "org.apache.spark.sql.delta.catalog.DeltaCatalog",
    )
    .getOrCreate()
    .createDataFrame(data, schema)
)

dataset = ExternalTableDataset(
    table="names_and_ages",
    write_mode="overwrite",
    location="abfss://container@storageaccount.dfs.core.windows.net/depts/cust",
)

dataset.save(spark_df)
reloaded = dataset.load()
assert Row(name="Bob", age=12) in reloaded.take(4)

Parameters:

  • table (str) –

    The name of the table.

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

    The name of the catalog in Unity. Defaults to None.

  • database (str, default: 'default' ) –

    The name of the database. (also referred to as schema). Defaults to "default".

  • format (str, default: 'delta' ) –

    The format of the table. Applicable only for external tables. Defaults to "delta".

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

    The mode to write the data into the table. If not present, the data set is read-only. Options are:["overwrite", "append", "upsert"]. "upsert" mode requires primary_key field to be populated. Defaults to None.

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

    The location of the table. Applicable only for external tables. Should be a valid path in an external location that has already been created. Defaults to None.

  • dataframe_type (str, default: 'spark' ) –

    "pandas" or "spark" dataframe. Defaults to "spark".

  • primary_key (str | list[str] | None, default: None ) –

    The primary key of the table. Can be in the form of a list. Defaults to None.

  • version (Version | None, default: None ) –

    kedro.io.core.Version instance to load the data. Defaults to None.

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

    The schema of the table in JSON form. Dataframes will be truncated to match the schema if provided. Used by the hooks to create the table if the schema is provided. Defaults to None.

  • partition_columns (list[str] | None, default: None ) –

    The columns to use for partitioning the table. Used by the hooks. Defaults to None.

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

    If table access control is enabled in your workspace, specifying owner_group will transfer ownership of the table and database to this owner. All databases should have the same owner_group. Defaults to None.

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

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

Raises: DatasetError: Invalid configuration supplied (through BaseTable validation).

Source code in kedro_datasets/databricks/_base_table_dataset.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def __init__(  # noqa: PLR0913
    self,
    *,
    table: str,
    catalog: str | None = None,
    database: str = "default",
    format: str = "delta",
    write_mode: str | None = None,
    location: str | None = None,
    dataframe_type: str = "spark",
    primary_key: str | list[str] | None = None,
    version: Version | None = None,
    # the following parameters are used by project hooks
    # to create or update table properties
    schema: dict[str, Any] | None = None,
    partition_columns: list[str] | None = None,
    owner_group: str | None = None,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Creates a new instance of ``BaseTableDataset``.

    Args:
        table: The name of the table.
        catalog: The name of the catalog in Unity.
            Defaults to None.
        database: The name of the database.
            (also referred to as schema). Defaults to "default".
        format: The format of the table.
            Applicable only for external tables.
            Defaults to "delta".
        write_mode: The mode to write the data into the table. If not
            present, the data set is read-only.
            Options are:["overwrite", "append", "upsert"].
            "upsert" mode requires primary_key field to be populated.
            Defaults to None.
        location: The location of the table.
            Applicable only for external tables.
            Should be a valid path in an external location that has already been created.
            Defaults to None.
        dataframe_type: "pandas" or "spark" dataframe.
            Defaults to "spark".
        primary_key: The primary key of the table.
            Can be in the form of a list. Defaults to None.
        version: kedro.io.core.Version instance to load the data.
            Defaults to None.
        schema: The schema of the table in JSON form.
            Dataframes will be truncated to match the schema if provided.
            Used by the hooks to create the table if the schema is provided.
            Defaults to None.
        partition_columns: The columns to use for partitioning the table.
            Used by the hooks. Defaults to None.
        owner_group: If table access control is enabled in your workspace,
            specifying owner_group will transfer ownership of the table and database to
            this owner. All databases should have the same owner_group. Defaults to None.
        metadata: Any arbitrary metadata.
            This is ignored by Kedro, but may be consumed by users or external plugins.
    Raises:
        DatasetError: Invalid configuration supplied (through ``BaseTable`` validation).
    """
    self._table = self._create_table(
        table=table,
        catalog=catalog,
        database=database,
        format=format,
        write_mode=write_mode,
        location=location,
        dataframe_type=dataframe_type,
        primary_key=primary_key,
        json_schema=schema,
        partition_columns=partition_columns,
        owner_group=owner_group,
    )

    self.metadata = metadata
    self._version = version

    super().__init__(
        filepath=None,  # type: ignore[arg-type]
        version=version,
        exists_function=self._exists,  # type: ignore[arg-type]
    )

metadata instance-attribute

metadata = metadata

load

load()

Loads the version of data in the format defined in the init (spark|pandas dataframe).

Raises:

  • VersionNotFoundError –

    If the version defined in the init doesn't exist.

Returns:

  • Union[DataFrame, DataFrame] –

    Returns a dataframe in the format defined in the init.

Source code in kedro_datasets/databricks/_base_table_dataset.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def load(self) -> DataFrame | pd.DataFrame:
    """Loads the version of data in the format defined in the init
    (spark|pandas dataframe).

    Raises:
        VersionNotFoundError: If the version defined in
            the init doesn't exist.

    Returns:
        Union[DataFrame, pd.DataFrame]: Returns a dataframe
            in the format defined in the init.
    """
    if self._version and self._version.load >= 0:
        try:
            data = (
                get_spark()
                .read.format("delta")
                .option("versionAsOf", self._version.load)
                .table(self._table.full_table_location())
            )
        except Exception as exc:
            raise VersionNotFoundError(self._version.load) from exc
    else:
        data = get_spark().table(self._table.full_table_location())
    if self._table.dataframe_type == "pandas":
        data = data.toPandas()
    return data

save

save(data)

Saves the data based on the write_mode and dataframe_type in the init. If write_mode is pandas, Spark dataframe is created first. If schema is provided, data is matched to schema before saving (columns will be sorted and truncated).

Parameters:

  • data (Any) –

    Spark or pandas dataframe to save to the table location.

Source code in kedro_datasets/databricks/_base_table_dataset.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def save(self, data: DataFrame | pd.DataFrame) -> None:
    """Saves the data based on the write_mode and dataframe_type in the init.
    If write_mode is pandas, Spark dataframe is created first.
    If schema is provided, data is matched to schema before saving
    (columns will be sorted and truncated).

    Args:
        data (Any): Spark or pandas dataframe to save to the table location.
    """
    if self._table.write_mode is None:
        raise DatasetError(
            "'save' can not be used in read-only mode. "
            f"Change 'write_mode' value to {', '.join(self._table._VALID_WRITE_MODES)}"
        )
    # filter columns specified in schema and match their ordering
    schema = self._table.schema()
    if schema:
        cols = schema.fieldNames()
        if self._table.dataframe_type == "pandas":
            data = get_spark().createDataFrame(
                data.loc[:, cols], schema=self._table.schema()
            )
        else:
            data = data.select(*cols)
    elif self._table.dataframe_type == "pandas":
        data = get_spark().createDataFrame(data)

    method = getattr(self, f"_save_{self._table.write_mode}", None)
    if method:
        method(data)

    primary_keys = (
        [self._table.primary_key]
        if isinstance(self._table.primary_key, str)
        else self._table.primary_key
    )

    if primary_keys and self._table._should_add_primary_key_constraint():
        self._table._add_primary_key_constraint(primary_keys)