---
title: Load data in pipelines
description: Load data into Lakeflow pipelines from cloud object storage, message buses, databases, and custom Python sources, using Auto Loader and streaming tables.
canonical_url: https://docs.databricks.com/aws/en/ldp/load
---

# Load data in pipelines

You can load data from any data source supported by Apache Spark on Databricks using pipelines. You can define datasets (tables and views) in a pipeline against any query that returns a Spark DataFrame, including streaming DataFrames and Pandas for Spark DataFrames. For data ingestion tasks, Databricks recommends using streaming tables for most use cases. Streaming tables are useful for ingesting data from cloud object storage using Auto Loader or from message buses like Kafka. For more about streaming tables, the primary dataset type for ingestion, see [Streaming tables](https://docs.databricks.com/aws/en/ldp/concepts/streaming-tables.md).

Not all data sources have SQL support for ingestion. However, you can mix SQL and Python sources in the same pipeline to use Python where needed. For details on working with libraries not packaged with pipelines by default, see [Manage Python dependencies for pipelines](https://docs.databricks.com/aws/en/ldp/developer/external-dependencies.md). For general information about ingestion in Databricks, see [Ingest with SQL and Spark APIs](https://docs.databricks.com/aws/en/ingestion/index.md).

The following examples demonstrate some common data loading patterns.

## <a id="identify-sources" />Identify your data sources and connection path

Before you write pipeline code, inventory every place data comes from. For each source, note how it exposes its data (files, a database, a software as a service (SaaS) system, an API, or a stream), how often it changes, and what credentials and network access it needs. The connection method often determines whether a source is naturally batch or streaming, so getting this right early avoids rework later.

Bucket each source into one of the following connection paths. The following table lists the preferred mechanism for each pipeline source:

| Source                                                                                           | Connection path                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Files landing in cloud object storage (S3, Azure Data Lake Storage, GCS)                         | The most common starting point. Use Auto Loader (`cloudFiles` format), which handles incremental discovery, schema inference, and schema evolution. See [Load files from cloud object storage](https://docs.databricks.com/aws/en/ldp/load.md#load-from-cloud).                                                                                                                                                                                                                                                              |
| Databases and SaaS applications (Salesforce, SQL Server, PostgreSQL, Workday)                    | Use a Lakeflow Connect managed connector where one exists for your source. Managed connectors are configuration-driven and handle authentication and incremental or CDC extraction for you. See [Lakeflow Connect connector concepts](https://docs.databricks.com/aws/en/ingestion/lakeflow-connect/index.md). If no managed connector exists for your source, ingest it directly or land its responses as files first. See [Ingest data from an API in pipelines](https://docs.databricks.com/aws/en/ldp/api-ingestion.md). |
| Message buses (Kafka, Kinesis, Azure Event Hubs, Pub/Sub)                                        | Read directly as a Structured Streaming source because these are native streaming sources. See [Load data from a message bus](https://docs.databricks.com/aws/en/ldp/load.md#load-from-message-bus).                                                                                                                                                                                                                                                                                                                         |
| Other Delta tables or Unity Catalog assets, including tables produced by other pipelines or jobs | Reference them directly and let Unity Catalog governance and lineage handle discovery and access. See [Load from an existing table](https://docs.databricks.com/aws/en/ldp/load.md#load-from-existing-table).                                                                                                                                                                                                                                                                                                                |
| Small or static reference data (lookup files, rarely-changing CSVs)                              | Load as a batch source in a materialized view. There's no benefit to streaming something that barely changes. See [Load small or static datasets from cloud object storage](https://docs.databricks.com/aws/en/ldp/load.md#load-small-or-static-datasets).                                                                                                                                                                                                                                                                   |
| An arbitrary HTTP or REST API with no managed connector                                          | Pull from the API in the pipeline or land its responses as files first. See [Ingest data from an API in pipelines](https://docs.databricks.com/aws/en/ldp/api-ingestion.md).                                                                                                                                                                                                                                                                                                                                                 |

For each source, confirm the following before you build:

* **Identity**: What the pipeline runs as. Pipelines can run as a service principal, so set this up first to avoid depending on a personal account.
* **Network path**: What connectivity the source needs, such as a storage credential, an external location, or Lakeflow Connect managed connectivity.
* **Change semantics**: How the source signals updates and deletes, if at all. This determines whether you need CDC or can treat the source as append-only.

## <a id="choose-format-and-storage" />Choose a file format and storage layer

Pipelines make most of this decision for you. Every streaming table and materialized view a pipeline creates is stored as a Delta table by default, which gives you ACID transactions, schema enforcement and evolution, time travel, and Unity Catalog governance and lineage on every dataset. You don't choose the format for pipeline outputs. Your real decisions are at the two edges of the pipeline:

* **Raw input format**: Whatever the source produces, such as CSV, JSON, or Parquet. Auto Loader and `read_files()` support these directly. Specify the format with `cloudFiles.format` in Python or the `format =>` argument in SQL. If you control the source, prefer Parquet or Avro, because they carry schema and compress better, which speeds up ingestion and schema inference. Pipelines handle any of these formats, so don't let format constrain your source choice.
* **Raw storage location**: For files, land data in a Unity Catalog volume rather than an ungoverned bucket path, so lineage and access control extend back to the landing zone. See [What are Unity Catalog volumes?](https://docs.databricks.com/aws/en/volumes/index.md).

For the tables a pipeline produces, your remaining choices are the target catalog and schema, which set the governance boundary and discoverability, and the physical layout of large tables. Use `CLUSTER BY` (liquid clustering) to keep query performance good as tables grow without hand-tuning partitions. See [Use liquid clustering for tables](https://docs.databricks.com/aws/en/tables/clustering.md).

## <a id="load-from-existing-table" />Load from an existing table

Load data from any existing table in Databricks. You can transform the data using a query or load the table for further processing in your pipeline.

### Python

```python
@dp.table(
  comment="A table summarizing counts of the top baby names for New York for 2021."
)
def top_baby_names_2021():
  return (
    spark.read.table("baby_names_prepared")
      .filter(expr("Year_Of_Birth == 2021"))
      .groupBy("First_Name")
      .agg(sum("Count").alias("Total_Count"))
      .sort(desc("Total_Count"))
  )
```

### SQL

```sql
CREATE OR REFRESH MATERIALIZED VIEW top_baby_names_2021
COMMENT "A table summarizing counts of the top baby names for New York for 2021."
AS SELECT
  First_Name,
  SUM(Count) AS Total_Count
FROM baby_names_prepared
WHERE Year_Of_Birth = 2021
GROUP BY First_Name
ORDER BY Total_Count DESC
```

## <a id="load-from-cloud" />Load files from cloud object storage

Databricks recommends using Auto Loader in pipelines for most data ingestion tasks from cloud object storage or from files in a Unity Catalog volume. Auto Loader and pipelines are designed to incrementally and idempotently load ever-growing data as it arrives in cloud storage. See [What is Auto Loader?](https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/index.md) and [Load data from object storage](https://docs.databricks.com/aws/en/ldp/developer/sql-dev.md#auto-loader-sql).

The following example reads data from cloud storage using Auto Loader.

### Python

```python
@dp.table
def customers():
  return (
    spark.readStream.format("cloudFiles")
      .option("cloudFiles.format", "json")
      .load("s3://mybucket/analysis/*/*/*.json")
  )
```

### SQL

```sql
CREATE OR REFRESH STREAMING TABLE sales
  AS SELECT *
  FROM STREAM read_files(
  's3://mybucket/analysis/*/*/*.json',
    format => "json"
  );
```

The following examples use Auto Loader to create datasets from CSV files in a Unity Catalog volume.

### Python

```python
@dp.table
def customers():
  return (
    spark.readStream.format("cloudFiles")
      .option("cloudFiles.format", "csv")
      .load("/Volumes/my_catalog/retail_org/customers/")
  )
```

### SQL

```sql
CREATE OR REFRESH STREAMING TABLE customers
AS SELECT * FROM STREAM read_files(
  "/Volumes/my_catalog/retail_org/customers/",
  format => "csv"
)
```

> [!NOTE]
>
> * If you use Auto Loader with file notifications and run a full refresh for your pipeline or streaming table, you must manually clean up your resources. You can use the [CloudFilesResourceManager](https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/file-notification-mode.md#cloud-resource-management) in a notebook to perform cleanup.
> * To load files with Auto Loader in a Unity Catalog enabled pipeline, you must use [external locations](https://docs.databricks.com/aws/en/connect/unity-catalog/cloud-storage/index.md#external-locations). To learn more about using Unity Catalog with pipelines, see [Use Unity Catalog with pipelines](https://docs.databricks.com/aws/en/ldp/unity-catalog.md).

### Authenticate to cloud storage

Auto Loader uses Unity Catalog external locations to authenticate against cloud storage. You must configure an external location for the storage path you want to read from and grant the `READ FILES` privilege to the executing user.

To ingest from Amazon S3, configure an external location backed by a storage credential that references an S3 bucket. For more information, see [Connect to cloud object storage using Unity Catalog](https://docs.databricks.com/aws/en/connect/unity-catalog/cloud-storage/index.md).

## <a id="load-from-message-bus" />Load data from a message bus

For low-latency ingestion from message buses, streaming tables in a [continuous pipeline](https://docs.databricks.com/aws/en/ldp/concepts/pipeline-mode.md) process new data as it arrives. [Serverless compute](https://docs.databricks.com/aws/en/ldp/serverless.md) manages compute and scaling, while pipelines on classic compute can use [enhanced autoscaling](https://docs.databricks.com/aws/en/ldp/auto-scaling.md).

For example, the following code configures a streaming table to ingest data from Kafka using the [read\_kafka](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_kafka.md) function.

### Python

```python
from pyspark import pipelines as dp

@dp.table
def kafka_raw():
  return (
    spark.readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "kafka_server:9092")
      .option("subscribe", "topic1")
      .load()
  )
```

### SQL

```sql
CREATE OR REFRESH STREAMING TABLE kafka_raw AS
  SELECT *
  FROM STREAM read_kafka(
    bootstrapServers => 'kafka_server:9092',
    subscribe => 'topic1'
  );
```

### Ingest from Google Pub/Sub

The following example creates a streaming table that reads from a Google Pub/Sub topic using the [read\_pubsub](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_pubsub.md) function.

#### Python

```python
@dp.table
def pubsub_raw():
  auth_options = {
    "clientId": client_id,
    "clientEmail": client_email,
    "privateKey": private_key,
    "privateKeyId": private_key_id
  }
  return (
    spark.readStream
      .format("pubsub")
      .option("subscriptionId", "my-subscription")
      .option("topicId", "my-topic")
      .option("projectId", "my-project")
      .options(auth_options)
      .load()
  )
```

#### SQL

```sql
CREATE OR REFRESH STREAMING TABLE pubsub_raw
AS SELECT * FROM STREAM read_pubsub(
  subscriptionId => 'my-subscription',
  projectId => 'my-project',
  topicId => 'my-topic',
  clientEmail => secret('pubsub-scope', 'clientEmail'),
  clientId => secret('pubsub-scope', 'clientId'),
  privateKeyId => secret('pubsub-scope', 'privateKeyId'),
  privateKey => secret('pubsub-scope', 'privateKey')
);
```

Databricks recommends using secrets when providing authorization options. See [Configure access to Pub/Sub](https://docs.databricks.com/aws/en/connect/streaming/pub-sub.md#access) for all authentication options.

To ingest from other message bus sources, see:

* Kinesis: [read\_kinesis](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_kinesis.md)
* Pulsar: [read\_pulsar](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_pulsar.md)

## <a id="load-from-azure-event-hubs" />Load data from Azure Event Hubs

Azure Event Hubs is a data streaming service that provides an Apache Kafka compatible interface. You can use the Structured Streaming Kafka connector, included in the pipeline runtime, to load messages from Azure Event Hubs. To learn more about loading and processing messages from Azure Event Hubs, see [Use Azure Event Hubs as a pipeline data source](https://docs.databricks.com/aws/en/ldp/event-hubs.md).

## <a id="load-from-external-systems" />Load data from external systems

Pipelines support loading data from any data source supported by Databricks. See [Connect to data sources and external services](https://docs.databricks.com/aws/en/connect/index.md). You can also load external data using Lakehouse Federation for [supported data sources](https://docs.databricks.com/aws/en/query-federation/database-federation.md#connection-types). Because Lakehouse Federation requires Databricks Runtime 13.3 LTS or above, to use Lakehouse Federation, configure your pipeline to use the [preview channel](https://docs.databricks.com/aws/en/ldp/properties.md#config-settings).

Some data sources don't have equivalent SQL support. If you cannot use Lakehouse Federation with one of these data sources, you can use Python to ingest data from the source. You can add Python and SQL source files to the same pipeline. The following example declares a materialized view to access the current state of data in a remote PostgreSQL table.

```python
from pyspark import pipelines as dp

@dp.table
def postgres_raw():
  return (
    spark.read
      .format("postgresql")
      .option("dbtable", table_name)
      .option("host", database_host_url)
      .option("port", 5432)
      .option("database", database_name)
      .option("user", username)
      .option("password", password)
      .load()
  )
```

## <a id="load-small-or-static-datasets" />Load small or static datasets from cloud object storage

You can load small or static datasets using Apache Spark load syntax. Pipelines support all of the file formats supported by Apache Spark on Databricks. For a full list, see [Data format options](https://docs.databricks.com/aws/en/query/formats/index.md).

The following examples demonstrate loading JSON to create a table.

### Python

```python
@dp.table
def clickstream_raw():
  return (spark.read.format("json").load("/databricks-datasets/wikipedia-datasets/data-001/clickstream/raw-uncompressed-json/2015_2_clickstream.json"))
```

### SQL

```sql
CREATE OR REFRESH MATERIALIZED VIEW clickstream_raw
AS SELECT * FROM read_files(
  "/databricks-datasets/wikipedia-datasets/data-001/clickstream/raw-uncompressed-json/2015_2_clickstream.json"
)
```

> [!NOTE]
>
> The `read_files` SQL function is common to all SQL environments on Databricks. It is the recommended pattern for direct file access using SQL in pipelines. For more information, see [Options](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_files.md#options).

## <a id="python-data-source" />Load data from a Python custom data source

Python custom data sources allow you to load data in custom formats. You can write code to read from and write to a specific external data source or use your existing Python code to read data from your own internal systems. For more detail about developing Python data sources, see [PySpark custom data sources](https://docs.databricks.com/aws/en/pyspark/datasources.md).

The following example registers a custom data source with the format name `my_custom_datasource` and reads from it in both batch and streaming modes.

```python
from pyspark import pipelines as dp

# Assume `my_custom_datasource` is a custom Python custom data
# source that supports both batch and streaming reads, and has
# been registered using `spark.dataSource.register`.

# This creates a materialized view
@dp.table(name = "read_from_batch")
def read_from_batch():
    return spark.read.format("my_custom_datasource").load()

# This creates a streaming table
@dp.table(name = "read_from_streaming")
def read_from_streaming():
    return spark.readStream.format("my_custom_datasource").load()
```

## <a id="ignore-changes" />Configure a streaming table to ignore changes in a source streaming table

By default, streaming tables require append-only sources. If your source streaming table requires updates or deletes (for example, for GDPR “right to be forgotten” processing), use the `skipChangeCommits` flag to ignore those changes. This flag works only with `spark.readStream` using the `option()` function and cannot be used when the source streaming table is the target of a [create\_auto\_cdc\_flow()](https://docs.databricks.com/aws/en/ldp/developer/ldp-python-ref-apply-changes.md) function. For more information, see [Handle changes to source Delta Lake tables](https://docs.databricks.com/aws/en/structured-streaming/delta-lake.md#ignore-changes).

```python
@dp.table
def b():
   return spark.readStream.option("skipChangeCommits", "true").table("A")
```

## <a id="configure-secrets" />Securely access storage credentials with secrets in a pipeline

You can use Databricks [secrets](https://docs.databricks.com/aws/en/security/secrets/index.md) to store credentials such as access keys or passwords. To configure the secret in your pipeline, use a Spark property in the pipeline settings cluster configuration. See [Configure classic compute for pipelines](https://docs.databricks.com/aws/en/ldp/configure-compute.md).

The following example uses a secret to store an access key required to read input data from an Azure Data Lake Storage storage account using Auto Loader. You can use this same method to configure any secret required by your pipeline, for example, AWS keys to access S3, or the password to an Apache Hive metastore.

To learn more about working with Azure Data Lake Storage, see [Connect to Azure Data Lake Storage and Blob Storage](https://docs.databricks.com/aws/en/connect/storage/azure-storage.md).

> [!NOTE]
>
> You must add the `spark.hadoop.` prefix to the `spark_conf` configuration key that sets the secret value.

```json
{
  "id": "43246596-a63f-11ec-b909-0242ac120002",
  "storage": "abfss://<container-name>@<storage-account-name>.dfs.core.windows.net/<path>",
  "clusters": [
    {
      "spark_conf": {
        "spark.hadoop.fs.azure.account.key.<storage-account-name>.dfs.core.windows.net": "{{secrets/<scope-name>/<secret-name>}}"
      },
      "autoscale": {
        "min_workers": 1,
        "max_workers": 5,
        "mode": "ENHANCED"
      }
    }
  ],
  "development": true,
  "continuous": false,
  "libraries": [
    {
      "notebook": {
        "path": "/Users/user@databricks.com/Pipeline Notebooks/pipeline quickstart"
      }
    }
  ],
  "name": "pipeline quickstart using ADLS2"
}
```

In this code sample, replace the following values.

| Placeholder              | Replace with                                                         |
| ------------------------ | -------------------------------------------------------------------- |
| `<container-name>`       | The name of the Azure storage account container.                     |
| `<storage-account-name>` | The ADLS storage account name.                                       |
| `<path>`                 | The path for pipeline output data and metadata.                      |
| `<scope-name>`           | The Databricks secret scope name.                                    |
| `<secret-name>`          | The name of the key containing the Azure storage account access key. |

```python
from pyspark import pipelines as dp

json_path = "abfss://<container-name>@<storage-account-name>.dfs.core.windows.net/<path-to-input-dataset>"
@dp.create_table(
  comment="Data ingested from an ADLS2 storage account."
)
def read_from_ADLS2():
  return (
    spark.readStream.format("cloudFiles")
      .option("cloudFiles.format", "json")
      .load(json_path)
  )
```

In this code sample, replace the following values.

| Placeholder               | Replace with                                                                |
| ------------------------- | --------------------------------------------------------------------------- |
| `<container-name>`        | The name of the Azure storage account container that stores the input data. |
| `<storage-account-name>`  | The ADLS storage account name.                                              |
| `<path-to-input-dataset>` | The path to the input dataset.                                              |
