---
title: Common data loading patterns
description: Learn common data loading patterns leveraging Auto Loader.
canonical_url: https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/patterns
---

# Common data loading patterns

Auto Loader simplifies a number of common data ingestion tasks. This quick reference provides examples for several popular patterns.

## Ingest data from cloud object storage as variant

Auto Loader can load all data from the supported file sources as a single `VARIANT` column in a target table. Because `VARIANT` is flexible to schema and type changes and maintains case sensitivity and `NULL` values present in the data source, this pattern is robust to most ingestion scenarios. For details, see [ Ingest data from cloud object storage as variant](https://docs.databricks.com/aws/en/ingestion/variant.md#auto-loader).

## Filtering directories or files using glob patterns

Glob patterns can be used for filtering directories and files when provided in the path.

| Pattern          | Description                                                                                                                                                      |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `?`              | Matches any single character                                                                                                                                     |
| `*`              | Matches zero or more characters                                                                                                                                  |
| `[abc]`          | Matches a single character from character set \{a,b,c}.                                                                                                          |
| `[a-z]`          | Matches a single character from the character range \{a…z}.                                                                                                      |
| `[^a]`           | Matches a single character that is not from character set or range \{a}. Note that the `^` character must occur immediately to the right of the opening bracket. |
| `{ab,cd}`        | Matches a string from the string set \{ab, cd}.                                                                                                                  |
| `{ab,c{de, fh}}` | Matches a string from the string set \{ab, cde, cfh}.                                                                                                            |

Use the `path` for providing prefix patterns, for example:

### Python

```python
df = spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", <format>) \
  .schema(schema) \
  .load("/Volumes/catalog_name/schema_name/volume_name/*/files")
```

### Scala

```scala
val df = spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", <format>)
  .schema(schema)
  .load("/Volumes/catalog_name/schema_name/volume_name/*/files")
```

You must use the option `pathGlobFilter` to explicitly provide suffix patterns. The `path` only provides a prefix filter. For example, if you would like to parse only `png` files in a directory that contains files with different suffixes, you can do the following:

### Python

```python
df = spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "binaryFile") \
  .option("pathGlobfilter", "*.png") \
  .load("/Volumes/catalog_name/schema_name/volume_name/path")
```

### Scala

```scala
val df = spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "binaryFile")
  .option("pathGlobfilter", "*.png")
  .load("/Volumes/catalog_name/schema_name/volume_name/path")
```

> [!NOTE]
>
> The default globbing behavior of Auto Loader is different than the default behavior of other Spark file sources. Add `.option("cloudFiles.useStrictGlobber", "true")` to your read to use globbing that matches default Spark behavior against file sources. See the following table for more on globbing:
>
> | Pattern              | File path             | Default globber | Strict globber |
> | -------------------- | --------------------- | --------------- | -------------- |
> | /a/b                 | /a/b/c/file.txt       | *Yes*           | *Yes*          |
> | /a/b                 | /a/b\_dir/c/file.txt  | *No*            | *No*           |
> | /a/b                 | /a/b.txt              | *No*            | *No*           |
> | /a/b/                | /a/b.txt              | *No*            | *No*           |
> | /a/\*/c/             | /a/b/c/file.txt       | *Yes*           | *Yes*          |
> | /a/\*/c/             | /a/b/c/d/file.txt     | *Yes*           | *Yes*          |
> | /a/\*/c/             | /a/b/x/y/c/file.txt   | *Yes*           | *No*           |
> | /a/\*/c              | /a/b/c\_file.txt      | *Yes*           | *No*           |
> | /a/\*/c/             | /a/b/c\_file.txt      | *Yes*           | *No*           |
> | /a/\*/c/             | /a/\*/cookie/file.txt | *Yes*           | *No*           |
> | /a/b\*               | /a/b.txt              | *Yes*           | *Yes*          |
> | /a/b\*               | /a/b/file.txt         | *Yes*           | *Yes*          |
> | /a/\{0.txt,1.txt}    | /a/0.txt              | *Yes*           | *Yes*          |
> | /a/\*/\{0.txt,1.txt} | /a/0.txt              | *No*            | *No*           |
> | /a/b/\[cde-h]/i/     | /a/b/c/i/file.txt     | *Yes*           | *Yes*          |

## Enable easy ETL

An easy way to get your data into Delta Lake without losing any data is to use the following pattern and enabling schema inference with Auto Loader. Databricks recommends running the following code in a Databricks job for it to automatically restart your stream when the schema of your source data changes. By default, the schema is inferred as string types, any parsing errors (there should be none if everything remains as a string) will go to `_rescued_data`, and any new columns will fail the stream and evolve the schema.

### Python

```python
spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "json") \
  .option("cloudFiles.schemaLocation", "<path-to-schema-location>") \
  .load("/Volumes/catalog_name/schema_name/volume_name/source_data") \
  .writeStream \
  .option("mergeSchema", "true") \
  .option("checkpointLocation", "<path-to-checkpoint>") \
  .start("<path_to_target>")
```

### Scala

```scala
spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "json")
  .option("cloudFiles.schemaLocation", "<path-to-schema-location>")
  .load("/Volumes/catalog_name/schema_name/volume_name/source_data")
  .writeStream
  .option("mergeSchema", "true")
  .option("checkpointLocation", "<path-to-checkpoint>")
  .start("<path_to_target>")
```

## Prevent data loss in well-structured data

When you know your schema but want to capture unexpected data, Databricks recommends using the `rescuedDataColumn`.

### Python

```python
# will collect all new fields as well as data type mismatches in _rescued_data
spark.readStream.format("cloudFiles") \
  .schema(expected_schema) \
  .option("cloudFiles.format", "json") \
  .option("cloudFiles.schemaEvolutionMode", "rescue") \
  .load("/Volumes/catalog_name/schema_name/volume_name/source_data") \
  .writeStream \
  .option("checkpointLocation", "<path-to-checkpoint>") \
  .start("<path_to_target>")
```

### Scala

```scala
spark.readStream.format("cloudFiles")
  .schema(expected_schema)
  .option("cloudFiles.format", "json")
  // will collect all new fields as well as data type mismatches in _rescued_data
  .option("cloudFiles.schemaEvolutionMode", "rescue")
  .load("/Volumes/catalog_name/schema_name/volume_name/source_data")
  .writeStream
  .option("checkpointLocation", "<path-to-checkpoint>")
  .start("<path_to_target>")
```

If you want your stream to stop processing if a new field is introduced that doesn't match your schema, you can add:

```python
.option("cloudFiles.schemaEvolutionMode", "failOnNewColumns")
```

## Enable flexible semi-structured data pipelines

When you're receiving data from a vendor that introduces new columns to the information they provide, you may not be aware of exactly when they do it, or you may not have the bandwidth to update your data pipeline. You can now leverage schema evolution to restart the stream and let Auto Loader update the inferred schema automatically. You can also leverage `schemaHints` for some of the "schemaless" fields that the vendor may be providing.

### Python

```python
spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "json") \
  # will ensure that the headers column gets processed as a map
  .option("cloudFiles.schemaHints",
          "headers map<string,string>, statusCode SHORT") \
  .load("/Volumes/catalog_name/schema_name/volume_name/api/requests") \
  .writeStream \
  .option("mergeSchema", "true") \
  .option("checkpointLocation", "<path-to-checkpoint>") \
  .start("<path_to_target>")
```

### Scala

```scala
spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "json")
  // will ensure that the headers column gets processed as a map
  .option("cloudFiles.schemaHints",
          "headers map<string,string>, statusCode SHORT")
  .load("/Volumes/catalog_name/schema_name/volume_name/api/requests")
  .writeStream
  .option("mergeSchema", "true")
  .option("checkpointLocation", "<path-to-checkpoint>")
  .start("<path_to_target>")
```

## Transform nested JSON data

Because Auto Loader infers the top level JSON columns as strings, you can be left with nested JSON objects that require further transformations. You can use the [semi-structured data access APIs](https://docs.databricks.com/aws/en/semi-structured/json.md) to further transform complex JSON content.

### Python

```python
spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "json") \
  # The schema location directory keeps track of your data schema over time
  .option("cloudFiles.schemaLocation", "<path-to-checkpoint>") \
  .load("/Volumes/catalog_name/schema_name/volume_name/nested_json") \
  .selectExpr(
    "*",
    "tags:page.name",    # extracts {"tags":{"page":{"name":...}}}
    "tags:page.id::int", # extracts {"tags":{"page":{"id":...}}} and casts to int
    "tags:eventType"     # extracts {"tags":{"eventType":...}}
  )
```

### Scala

```scala
spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "json")
  // The schema location directory keeps track of your data schema over time
  .option("cloudFiles.schemaLocation", "<path-to-checkpoint>")
  .load("/Volumes/catalog_name/schema_name/volume_name/nested_json")
  .selectExpr(
    "*",
    "tags:page.name",     // extracts {"tags":{"page":{"name":...}}}
    "tags:page.id::int",  // extracts {"tags":{"page":{"id":...}}} and casts to int
    "tags:eventType"      // extracts {"tags":{"eventType":...}}
  )
```

## Infer nested JSON data

When you have nested data, you can use the `cloudFiles.inferColumnTypes` option to infer the nested structure of your data and other column types.

### Python

```python
spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "json") \
  # The schema location directory keeps track of your data schema over time
  .option("cloudFiles.schemaLocation", "<path-to-checkpoint>") \
  .option("cloudFiles.inferColumnTypes", "true") \
  .load("/Volumes/catalog_name/schema_name/volume_name/nested_json")
```

### Scala

```scala
spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "json")
  // The schema location directory keeps track of your data schema over time
  .option("cloudFiles.schemaLocation", "<path-to-checkpoint>")
  .option("cloudFiles.inferColumnTypes", "true")
  .load("/Volumes/catalog_name/schema_name/volume_name/nested_json")
```

## Load CSV files without headers

The following example shows how to load CSV files without headers using Auto Loader. Use `rescuedDataColumn` to capture any data that doesn't match the provided schema.

### Python

```python
df = spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "csv") \
  .option("rescuedDataColumn", "_rescued_data") \ # ensure that you don't lose data
  .schema(<schema>) \ # provide a schema here for the files
  .load(<path>)
```

### Scala

```scala
val df = spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "csv")
  .option("rescuedDataColumn", "_rescued_data") // makes sure that you don't lose data
  .schema(<schema>) // provide a schema here for the files
  .load(<path>)
```

## Enforce a schema on CSV files with headers

The following example shows how to enforce a schema on CSV files that include headers. Use `rescuedDataColumn` to capture any data that doesn't match the provided schema.

### Python

```python
df = spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "csv") \
  .option("header", "true") \
  .option("rescuedDataColumn", "_rescued_data") \ # makes sure that you don't lose data
  .schema(<schema>) \ # provide a schema here for the files
  .load(<path>)
```

### Scala

```scala
val df = spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "csv")
  .option("header", "true")
  .option("rescuedDataColumn", "_rescued_data") // makes sure that you don't lose data
  .schema(<schema>) // provide a schema here for the files
  .load(<path>)
```

## <a id="image" />Ingest image or binary data to Delta Lake for ML

Once the data is stored in Delta Lake, you can run distributed inference on the data. See [Perform distributed inference using pandas UDF](https://docs.databricks.com/aws/en/machine-learning/reference-solutions/images-etl-inference.md#perform-distributed-inference-using-pandas-udf).

### Python

```python
spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "binaryFile") \
  .load("/Volumes/catalog_name/schema_name/volume_name/images") \
  .writeStream \
  .option("checkpointLocation", "<path-to-checkpoint>") \
  .start("<path_to_target>")
```

### Scala

```scala
spark.readStream.format("cloudFiles")
  .option("cloudFiles.format", "binaryFile")
  .load("/Volumes/catalog_name/schema_name/volume_name/images")
  .writeStream
  .option("checkpointLocation", "<path-to-checkpoint>")
  .start("<path_to_target>")
```

## <a id="pipeline-syntax" />Auto Loader syntax for Lakeflow pipelines

Lakeflow pipelines provide slightly modified Python syntax for Auto Loader and add SQL support for Auto Loader. The following examples use Auto Loader to create datasets from JSON files using the [Wanderbricks](https://docs.databricks.com/aws/en/discover/wanderbricks-dataset.md) sample travel booking dataset:

### Python

```python
@dp.table
def booking_updates():
  return (
    spark.readStream.format("cloudFiles")
      .option("cloudFiles.format", "json")
      .option("multiLine", "true")
      .load("/Volumes/my_catalog/my_schema/my_volume/wanderbricks/booking_updates")
  )

@dp.table
def reviews():
  return (
    spark.readStream.format("cloudFiles")
      .option("cloudFiles.format", "json")
      .option("multiLine", "true")
      .load("/Volumes/my_catalog/my_schema/my_volume/wanderbricks/reviews")
  )
```

### SQL

```sql
CREATE OR REFRESH STREAMING TABLE booking_updates
AS SELECT * FROM STREAM read_files(
  "/Volumes/my_catalog/my_schema/my_volume/wanderbricks/booking_updates",
  format => "json",
  multiLine => true
)

CREATE OR REFRESH STREAMING TABLE reviews
AS SELECT * FROM STREAM read_files(
  "/Volumes/my_catalog/my_schema/my_volume/wanderbricks/reviews",
  format => "json",
  multiLine => true
)
```

You can use supported format options for Auto Loader. Options for `read_files` are key-value pairs. For details on supported formats and options, see [Options](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_files.md#options).

```sql
CREATE OR REFRESH STREAMING TABLE my_table
AS SELECT *
  FROM STREAM read_files(
    "/Volumes/my_volume/path/to/files/*",
    option-key => option-value,
    ...
  )
```

The following example reads multiline JSON files with column type inference enabled:

```sql
CREATE OR REFRESH STREAMING TABLE booking_updates
AS SELECT * FROM STREAM read_files(
  "/Volumes/my_catalog/my_schema/my_volume/wanderbricks/booking_updates",
  format => "json",
  multiLine => true,
  inferColumnTypes => true
)
```

You can use the `schema` to specify the format manually; you must specify the `schema` for formats that do not support [schema inference](https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/schema.md):

### Python

```python
@dp.table
def booking_updates_raw():
  return (
    spark.readStream.format("cloudFiles")
      .schema("booking_id LONG, booking_update_id LONG, user_id LONG, property_id LONG, status STRING, guests_count INT, total_amount DOUBLE, check_in DATE, check_out DATE, created_at TIMESTAMP, updated_at TIMESTAMP")
      .option("cloudFiles.format", "json")
      .option("multiLine", "true")
      .load("/Volumes/my_catalog/my_schema/my_volume/wanderbricks/booking_updates")
  )
```

### SQL

```sql
CREATE OR REFRESH STREAMING TABLE booking_updates_raw
AS SELECT *
FROM STREAM read_files(
  "/Volumes/my_catalog/my_schema/my_volume/wanderbricks/booking_updates",
  format => "json",
  multiLine => true,
  schema => "booking_id LONG, booking_update_id LONG, user_id LONG, property_id LONG, status STRING, guests_count INT, total_amount DOUBLE, check_in DATE, check_out DATE, created_at TIMESTAMP, updated_at TIMESTAMP"
)
```

> [!NOTE]
>
> Lakeflow pipelines automatically configure and manage the schema and checkpoint directories when using Auto Loader to read files. However, if you manually configure either of these directories, performing a full refresh does not affect the contents of the configured directories. Databricks recommends using the automatically configured directories to avoid unexpected side effects during processing.

## <a id="additional-resources" /> Additional resources

* [What is Auto Loader?](https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/index.md)
* [Configure schema inference and evolution in Auto Loader](https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/schema.md)
* [Spark Declarative Pipelines on Lakeflow](https://docs.databricks.com/aws/en/ldp/index.md)
