donderdag 3 december 2026

Databricks series : Understanding schema flexibility with STRUCT, ARRAY, MAP and VARIANT

Introduction

When working with JSON data in Databricks, you will often encounter complex data types such as STRUCT, ARRAY, MAP and VARIANT.  At first glance, these types may look quite similar. They all allow you to work with nested or semi-structured data.  However, there is an important difference: how flexible is the structure of your data?


For example:

  • Can a JSON record contain a field that another record does not have?
  • Can an ARRAY contain a different number of elements?
  • Can a MAP contain different keys for each record?
  • Can every record have a completely different structure?

In this article, we will explore these questions and explain how STRUCT, ARRAY, MAP and VARIANT handle differences in data structures.


We are building upon what we already have :


STRUCT : A fixed structure with optional values

A STRUCT represents an object with a predefined set of named fields. For example, imagine that we define the following STRUCT:


STRUCT<
    customer_id: INT,
    name: STRING,
    country: STRING,
    email: STRING
>


We have defined four fields:

  • customer_id
  • name
  • country
  • email

Does this mean that every customer must have a value for all four fields? No. A field can contain NULL.



Sarah does not have an email address. That is perfectly valid.  The important distinction is that the email field is still part of the STRUCT definition. Its value is simply NULL. Key takeaway: STRUCT has a fixed schema, but individual field values can be NULL.


ARRAY : A collection with a consistent element type

An ARRAY represents a collection of elements. An important rule is that all elements in an ARRAY must have the same data type.  For example:


ARRAY<STRING>


The following values are valid:

["Dutch", "English", "French"]


An ARRAY can also contain NULL elements:

["Dutch", null, "French"]


The number of elements does not have to be the same in every record.  For example, one customer could have three languages while another customer has only one.


ARRAY containing STRUCTs

An ARRAY can also contain more complex elements, such as STRUCTs.


For example:

ARRAY<
    STRUCT<
        order_id: INT,
        amount: DECIMAL(10,2)
    >
>


This represents a list of orders.  Each order has the same structure:

  • order_id
  • amount

You can have different numbers of orders, but every order follows the same STRUCT definition. The amount field can still contain NULL if it is nullable. Key takeaway: ARRAY allows a variable number of elements, but the element type remains consistent.


MAP : Different keys for different records

A MAP is a collection of key-value pairs.  For example:

MAP<STRING, STRING>


This means: Keys are STRING values.  alues are STRING values.  But here is an important difference compared with STRUCT.  The actual keys do not have to be the same in every record.


Consider these two customer records.


Customer 1

{
    "language": "Dutch",
    "currency": "EUR"
}


Customer 2

{
    "language": "English",
    "theme": "dark"
}


Both records are valid MAP values. Customer 1 has a currency key, while customer 2 has a theme key. The MAP definition remains the same because both records use STRING keys and STRING values. If you try to retrieve a key that does not exist, the result is NULL.


For example:

SELECT
    element_at(preferences, 'currency') AS currency
FROM main.demo.customer_preferences;


For customer 2, this returns NULL because the currency key is not present.

Key takeaway: MAP has fixed key and value data types, but the actual keys can differ between records.


VARIANT : A completely flexible structure

VARIANT takes flexibility one step further. Unlike STRUCT, ARRAY and MAP, VARIANT does not require you to define the complete structure in advance. Each record can contain different fields, nested objects, arrays and values. Consider these three JSON records.


Record 1

{
    "customer_id": 1001,
    "name": "Jan",
    "country": "Netherlands"
}


Record 2

{
    "customer_id": 1002,
    "name": "Sarah",
    "preferences": {
        "language": "English"
    },
    "orders": [5001, 5002]
}


Record 3

{
    "customer_id": 1003,
    "name": "Peter",
    "email": "peter@example.com",
    "active": true
}


Notice that the three records have different structures.

  • Record 1 contains a country.

  • Record 2 contains preferences and an array of orders.

  • Record 3 contains an email address and an active flag.

All three records can be stored in the same VARIANT column.


For example:

CREATE OR REPLACE TABLE main.demo.customer_variant
(
    payload VARIANT
);


You can insert the JSON documents using PARSE_JSON():

INSERT INTO main.demo.customer_variant
VALUES
(
    PARSE_JSON(
        '{"customer_id":1001,"name":"Jan","country":"Netherlands"}'
    )
),
(
    PARSE_JSON(
        '{"customer_id":1002,"name":"Sarah","preferences":{"language":"English"},"orders":[5001,5002]}'
    )
),
(
    PARSE_JSON(
        '{"customer_id":1003,"name":"Peter","email":"peter@example.com","active":true}'
    )
);


You can then extract fields using the VARIANT path syntax:

SELECT
    payload:customer_id::INT AS customer_id,
    payload:name::STRING AS customer_name,
    payload:country::STRING AS country,
    payload:email::STRING AS email
FROM main.demo.customer_variant;


Fields that are not present in a particular record return NULL.  This makes VARIANT especially useful when ingesting data from external APIs or event streams where the JSON structure can change over time.


Key takeaway: VARIANT allows each record to have a different structure within the same column.


5. Comparing the four data types

Let's summarize the differences.




There is one important detail:

  • STRUCT has fixed field names, but values can be NULL.

  • ARRAY has a fixed element type, but the number of elements can vary.

  • MAP has fixed key and value types, but the actual keys can vary.

  • VARIANT allows the entire JSON structure to vary.


6. When should you use which data type?

A simple rule of thumb:


Use STRUCT when:

  • You know the fields in advance.

  • You want a clearly defined schema.

  • You are working with objects such as customer addresses or product details.


Use ARRAY when:

  • You have a list of repeating elements.

  • You want to store multiple values of the same type.

  • You are working with orders, transactions or event collections.


Use MAP when:

  • You have dynamic attributes.

  • The keys can differ between records.

  • You want to store flexible key-value pairs.


Use VARIANT when:

  • You do not know the complete JSON structure in advance.

  • The structure can change between records.

  • You are ingesting data from external APIs or event streams.


Conclusion

STRUCT, ARRAY, MAP and VARIANT all help us work with complex data in Databricks, but they offer different levels of flexibility. The main difference is not whether a value can be NULL. Even a STRUCT can contain NULL values. The real difference is how much of the data structure must be defined in advance. STRUCT, ARRAY and MAP have defined type structures, while VARIANT allows the complete structure to vary between records.This is particularly useful when designing a data ingestion process. You can initially store flexible JSON payloads using VARIANT and then extract and validate the fields you need in your Prep layer.


In other words:

Use VARIANT when you need flexibility at ingestion time, and use STRUCT, ARRAY and MAP when you want more explicitly defined data structures.


Starting a New Databricks AI Project: Creating a Dedicated Unity Catalog

 Introduction

I am starting a New Databricks AI Project and I will start with creating a dedicated Unity Catalog. When starting a new data engineering or AI project in Databricks, I prefer to begin with a clean and well-organized environment.  Rather than using an existing catalog or mixing the project with other experiments, I want to create a dedicated Unity Catalog catalog for the project.


In this blog post, I'll show how to create a new catalog in Databricks Free Edition and prepare the foundation for a larger Data Architecture and AI project.


We are building upon what we already have :


The project: Mortgage AI Lab

For this learning project, I will build a small but realistic mortgage data platform. The idea is to gradually develop a solution that combines:

  • Data Engineering with PySpark and SQL.
  • Delta Lake and the Medallion Architecture.
  • Data Modelling and Semantic Modelling.
  • Unity Catalog and Data Governance.
  • AI-powered analytics and AI Agents.


The ultimate goal is to make mortgage data accessible not only through traditional SQL queries and dashboards, but also through AI-powered applications that can understand and answer questions about the underlying business data.


Before building any pipelines or loading data, I want to establish a dedicated project structure.


Why create a separate catalog?

Databricks Unity Catalog provides a centralized way to organize and govern data assets. The hierarchy is:

Metastore → Catalog → Schema → Tables, Views and other objects


A catalog is a useful top-level boundary for organizing a project. By creating a dedicated catalog, I can:

  • Keep this project separate from existing exercises and datasets.
  • Organize data assets in a consistent way.
  • Apply permissions and governance independently.
  • Build a structure that can grow as the project evolves.

In my Databricks Free Edition workspace, I can already see several existing catalogs, including main, samples, system and workspace. However, I don't want to use any of these for my new project. Instead, I'll create a dedicated catalog called mortgage_ai_lab.


3. Creating the catalog

First, open a new notebook in your Databricks workspace. Select SQL as the notebook language and execute the following statement:

%sql
CREATE CATALOG IF NOT EXISTS mortgage_ai_lab
COMMENT 'Independent learning project for Databricks Data Architecture and AI';

SHOW CATALOGS;


The CREATE CATALOG statement creates the new catalog if it does not already exist. The COMMENT provides a short description of the catalog, explaining its purpose. Finally, SHOW CATALOGS lists the catalogs available in the current metastore. You should now see mortgage_ai_lab in the result.


Note: Creating a catalog requires the appropriate CREATE CATALOG privileges on the metastore. If you receive a permission error, check the permissions associated with your Databricks workspace and user.


Planning the project structure


The catalog is now created, but it does not contain any schemas or tables yet.


I plan to organize the project using a structure inspired by the Medallion Architecture:


mortgage_ai_lab
│
├── bronze
│   └── Raw source data
│
├── silver
│   └── Cleansed and validated data
│
├── gold
│   └── Business-ready and analytical data
│
└── ai
    └── AI-related assets and supporting data


Each of these folders will eventually become a separate Unity Catalog schema. This gives the project a clear separation between raw data, refined data, business-ready data and AI-related assets. I'll create these schemas in the next step.


What comes next?

With the catalog in place, the foundation of the project is ready.In the next part of this series, I'll create the schemas and start designing the mortgage domain.


The domain will include concepts such as:

  • Customers
  • Mortgages
  • Mortgage loan components
  • Properties used as collateral
  • Interest rates
  • Payments and repayments


From there, I'll build the data pipelines, develop the data models and eventually connect the data to AI capabilities.


The objective is not simply to build another Databricks pipeline. I want to explore how good data architecture, clear business definitions and semantic modelling can provide reliable context for AI applications and agents.


A good AI solution starts with well-structured and well-understood data.

zondag 29 november 2026

Databricks Series : Working with JSON in Databricks SQL : VARIANT

Introduction

In the previous articles, we explored three important complex data types in Databricks SQL: STRUCT, ARRAY and MAP. These types are useful when working with nested data. But what happens when the structure of your incoming JSON data is not always the same?


For example:

  • One JSON record contains a phone_number, while another does not.
  • A new API version introduces additional fields.
  • Different records contain different attributes.
  • You do not know the complete JSON structure in advance.


This is where the VARIANT data type becomes useful.In this article, we will explore what VARIANT is, how to store JSON data in a VARIANT column, and how to extract fields from it using Databricks SQL.


We are building upon what we already have :


What is VARIANT?

VARIANT is a data type designed for storing semi-structured data. Unlike a STRUCT, where you define the fields and their data types in advance, VARIANT allows you to store JSON data without having to define the complete structure first. For example, imagine that you receive these two JSON records:


record 1 

{
  "customer_id": 1001,
  "name": "Jan Jansen",
  "country": "Netherlands"
}


Record 2

{
  "customer_id": 1002,
  "name": "Sarah Johnson",
  "country": "USA",
  "email": "sarah@example.com",
  "preferences": {
    "language": "English",
    "newsletter": true
  }
}


Both records have some common fields, but the second record contains additional information. With a traditional STRUCT, you would need to define a schema that accommodates these fields. With VARIANT, you can store both JSON records in the same column without first defining all their fields.


This makes VARIANT particularly useful when working with:

  • REST APIs
  • JSON files
  • Event streams
  • Changing data structures
  • Semi-structured source data


2. Create a table with a VARIANT column

Let's start by creating a table in Databricks. We will store the customer information in a column called payload.


CREATE OR REPLACE TABLE main.demo.customer_variant
(
    payload VARIANT
);


Notice that we do not define individual columns for customer_id, name or country. The complete JSON document will be stored in the payload column.


Insert JSON data using PARSE_JSON

To convert a JSON string into a VARIANT value, Databricks provides the PARSE_JSON() function.

Let's insert two customer records.



INSERT INTO main.demo.customer_variant
VALUES
(
    PARSE_JSON(
        '{
            "customer_id": 1001,
            "name": "Jan Jansen",
            "country": "Netherlands"
        }'
    )
),
(
    PARSE_JSON(
        '{
            "customer_id": 1002,
            "name": "Sarah Johnson",
            "country": "USA",
            "email": "sarah@example.com",
            "preferences": {
                "language": "English",
                "newsletter": true
            }
        }'
    )
);


The PARSE_JSON() function converts the JSON string into a VARIANT value. You can now query the table:


SELECT *
FROM main.demo.customer_variant;


Results in :




The complete JSON document is stored in one column.


4. Extract fields from VARIANT

Storing the complete JSON document is useful, but in most cases you also want to access individual fields. Databricks SQL supports the colon (:) operator to navigate through VARIANT data.

For example:


SELECT
    payload:customer_id AS customer_id,
    payload:name AS customer_name,
    payload:country AS country
FROM main.demo.customer_variant;


Results in :



You may notice that the extracted values are still VARIANT values.


SELECT
    TYPEOF(payload) AS payload_type,
    TYPEOF(payload:customer_id) AS customer_id_type,
    TYPEOF(payload:name) AS name_type
FROM main.demo.customer_variant;


Resulting in : 



 If you want to work with them as regular SQL data types, you can cast them.


SELECT
    payload:customer_id::INT AS customer_id,
    payload:name::STRING AS customer_name,
    payload:country::STRING AS country
FROM main.demo.customer_variant;


Resulting in :




Now the extracted fields have explicit SQL data types.


5. Access nested fields

VARIANT also supports nested JSON structures. Remember that our second customer record contains a preferences object:


{
  "preferences": {
    "language": "English",
    "newsletter": true
  }
}


You can access nested fields using the same colon notation.


SELECT
    payload:customer_id::INT AS customer_id,
    payload:preferences:language::STRING AS language,
    payload:preferences:newsletter::BOOLEAN AS newsletter
FROM main.demo.customer_variant;


REsulting in : 




The result for the first customer will contain NULL values because that record does not have a preferences object. The second customer will return the language and newsletter preference. This is one of the benefits of VARIANT: records do not all need to contain exactly the same fields.


Access arrays inside VARIANT

VARIANT can also contain arrays. Let's insert another customer with a list of orders.


INSERT INTO main.demo.customer_variant
VALUES
(
    PARSE_JSON(
        '{
            "customer_id": 1003,
            "name": "Peter Smith",
            "country": "UK",
            "orders": [
                {
                    "order_id": 5001,
                    "amount": 125.50
                },
                {
                    "order_id": 5002,
                    "amount": 89.99
                }
            ]
        }'
    )
);


You can access an individual array element using its index. Remember that array indexing starts at zero.


SELECT
    payload:customer_id::INT AS customer_id,
    payload:orders[0]:order_id::INT AS first_order_id,
    payload:orders[0]:amount::DECIMAL(10,2) AS first_order_amount
FROM main.demo.customer_variant;


Resulting in :




This example retrieves the first order from the array.  If you want to retrieve all orders as separate rows, you can use VARIANT_EXPLODE. This turns the array elements into separate rows.  


Inspect the structure of VARIANT data

Sometimes you receive JSON data without knowing its exact structure. Databricks provides the SCHEMA_OF_VARIANT() function to inspect the structure of an individual VARIANT value.


SELECT
    SCHEMA_OF_VARIANT(payload) AS detected_schema
FROM main.demo.customer_variant;


This returns a schema description based on the contents of the VARIANT value. You can also use SCHEMA_OF_VARIANT_AGG() to derive a combined schema from multiple records.


SELECT
    SCHEMA_OF_VARIANT_AGG(payload) AS combined_schema
FROM main.demo.customer_variant;


Resulting in :





This can be helpful when exploring new or changing data sources.


8. Handle invalid JSON

What happens when the incoming JSON is not valid? For example:


{
  "customer_id": 1004,
  "name": "Invalid JSON"


The JSON document is missing a closing brace. Using PARSE_JSON() on malformed JSON raises an error.  If you prefer to return NULL instead of stopping the operation, you can use TRY_PARSE_JSON().


SELECT
    TRY_PARSE_JSON('{"customer_id": 1004, "name": "Invalid JSON"') AS payload;



This returns NULL when the JSON cannot be parsed. This can be useful when ingesting data from external systems where the input is not always reliable.


VARIANT versus STRUCT, ARRAY and MAP

We have now seen how VARIANT works. But when should you use it instead of STRUCT, ARRAY or MAP?




A simple rule of thumb:

  • Use STRUCT when you know the structure and want strongly typed fields.

  • Use ARRAY when you need an ordered list of values.

  • Use MAP when you need key-value pairs.

  • Use VARIANT when the structure of your incoming data can change or is not known in advance.

VARIANT does not mean that you should store every field in one JSON column forever. If you frequently query fields such as customer_id, country or event_timestamp, it is often better to extract those fields into regular typed columns. This makes the data easier to use in analytical queries and helps with data organization and performance.


Important considerations

There are a few things to keep in mind when using VARIANT in Databricks:

  • VARIANT is supported in Databricks SQL and Databricks Runtime 15.3 and above.
  • VARIANT is designed for semi-structured data such as JSON objects, arrays and scalar values.
  • JSON field names are case-sensitive.
  • A VARIANT column cannot be used as a partitioning or clustering key, or in operations such as GROUP BY and ORDER BY.
  • Frequently queried fields should generally be extracted into regular columns.

Always check the supported features of the Databricks Runtime or SQL warehouse you are using.


Conclusion

The VARIANT data type adds another useful option when working with semi-structured data in Databricks. Where STRUCT, ARRAY and MAP require you to work with defined data structures, VARIANT gives you more flexibility when the structure of your incoming JSON data is unknown or changes over time.  It is particularly useful in ingestion and raw data layers, where you may want to preserve the original payload before deciding how to transform and model it. Once the data is understood, you can extract the relevant fields and move them into structured tables for further processing and analytics.


In short: VARIANT gives you flexibility at ingestion time, while STRUCT, ARRAY and MAP provide more explicitly defined structures for working with your data.


zaterdag 28 november 2026

Databricks Series : Working with JSON in Databricks SQL : MAP

Introduction

A MAP is a collection of key-value pairs. It is similar to a Python dictionary. Unlike a STRUCT, a MAP is useful when the available keys may vary between records. 


We are building upon what we already have :


Example JSON

Imagine that a customer has several preferences:


{
  "customer_id": 1001,
  "preferences": {
    "language": "Dutch",
    "currency": "EUR",
    "newsletter": "true",
    "theme": "dark"
  }
}

The preferences property contains dynamic attributes. We can represent this using:


MAP<STRING, STRING>


This means that both the keys and values are strings. 


Create a source table


CREATE OR REPLACE TABLE main.demo.customer_map_json
(
    customer_id BIGINT,
    payload STRING
);


Insert an example record:


INSERT INTO main.demo.customer_map_json
VALUES (
    1001,
    '{
      "customer_id": 1001,
      "preferences": {
        "language": "Dutch",
        "currency": "EUR",
        "newsletter": "true",
        "theme": "dark"
      }
    }'
);


Parse the JSON

Use from_json() to convert the preferences object into a MAP.


SELECT
    from_json(
        payload,
        'STRUCT<
            customer_id: BIGINT,
            preferences: MAP<STRING, STRING>
        >'
    ) AS customer

FROM main.demo.customer_map_json;


Results in 




Now Spark understands that preferences is a MAP.


Extract individual values

We can retrieve values using element_at().


SELECT
    customer.customer_id,

    element_at(
        customer.preferences,
        'language'
    ) AS language,

    element_at(
        customer.preferences,
        'currency'
    ) AS currency,

    element_at(
        customer.preferences,
        'newsletter'
    ) AS newsletter,

    element_at(
        customer.preferences,
        'theme'
    ) AS theme

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                preferences: MAP<STRING, STRING>
            >'
        ) AS customer

    FROM main.demo.customer_map_json
);

Resulting in




Notice that we can retrieve individual values by specifying their keys. If a key does not exist, element_at() returns NULL.

Expand all MAP entries

Sometimes we don't know which keys are present. In that situation, we can use EXPLODE on the MAP itself.


SELECT
    customer.customer_id,
    preference_key,
    preference_value

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                preferences: MAP<STRING, STRING>
            >'
        ) AS customer

    FROM main.demo.customer_map_json
) parsed

LATERAL VIEW EXPLODE(customer.preferences)
    exploded AS preference_key, preference_value;


Results in : 





This is particularly useful when you want to inspect all available attributes without knowing the keys in advance.


Create a SQL View

For a fixed set of attributes, we can create a regular view:


CREATE OR REPLACE VIEW main.demo.v_customer_preferences AS

SELECT
    customer.customer_id,

    element_at(
        customer.preferences,
        'language'
    ) AS language,

    element_at(
        customer.preferences,
        'currency'
    ) AS currency,

    element_at(
        customer.preferences,
        'newsletter'
    ) AS newsletter,

    element_at(
        customer.preferences,
        'theme'
    ) AS theme

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                preferences: MAP<STRING, STRING>
            >'
        ) AS customer

    FROM main.demo.customer_map_json
);


Query the view:

SELECT *
FROM main.demo.v_customer_preferences;




MAP is useful for dynamic attributes where you cannot always predict which keys will be available.

Examples include:

  • Customer preferences
  • Product attributes
  • API metadata
  • Event properties
  • Dynamic configuration values

If the keys are known and stable, a STRUCT is often a better choice because it provides a clearly defined schema


4. Comparing STRUCT, ARRAY and MAP

We have now seen all three complex data types.



A simple way to remember the difference:

  • STRUCT: one object with multiple attributes.
  • ARRAY: multiple elements, often repeating objects.
  • MAP: dynamically named attributes.


Choosing the right approach for your Databricks architecture


When working with JSON in a Medallion Architecture, I would generally separate the responsibilities.


Raw layer

Keep the original JSON data. This preserves the source information and allows you to reprocess it if the schema changes.


Base layer

Store the ingested data in Delta tables. Depending on the ingestion design, the JSON can remain a STRING or be parsed into complex Spark types.


Prep layer

Parse the JSON using from_json(), validate the structure and extract the attributes needed for downstream processing.


Gold layer

Expose business-friendly SQL Views or tables with clear relational columns.


RAW
 |
 | Original JSON
 v
BASE
 |
 | Delta tables
 v
PREP
 |
 | STRUCT / ARRAY / MAP parsing
 | Data validation
 v
GOLD
 |
 | SQL Views
 | Business-ready columns
 v
Reporting / Analytics


Conclusion

Databricks SQL provides powerful functionality for working with semi-structured JSON data. With from_json(), we can convert JSON strings into typed structures. We can then use dot notation to access STRUCT fields, EXPLODE() to expand ARRAY elements and ELEMENT_AT() to retrieve values from MAPs. Instead of keeping complex JSON documents in a single column, we can expose the information through reusable SQL Views. 


The key is to understand the structure of the JSON first and choose the appropriate Spark data type. Once you understand STRUCT, ARRAY and MAP, working with nested JSON in Databricks becomes much easier.

Databricks series : Working with JSON in Databricks SQL : ARRAY

Introduction

An ARRAY represents a collection of elements. A common example is an order list belonging to a customer. One customer can have multiple orders, and each order contains several attributes.


We are building upon what we already have :


An example 


{
  "customer_id": 1001,
  "name": "Jan Jansen",
  "orders": [
    {
      "order_id": "ORD001",
      "amount": 125.50,
      "status": "COMPLETED"
    },
    {
      "order_id": "ORD002",
      "amount": 89.95,
      "status": "OPEN"
    }
  ]
}


The orders property is an ARRAY.

Each element inside the ARRAY is a STRUCT containing:

  • order_id

  • amount

  • status

The resulting Spark data type is conceptually:


Create a source table

Lets create a table :

CREATE OR REPLACE TABLE main.demo.customer_array_json
(
    customer_id BIGINT,
    payload STRING
);

Insert the example data:


INSERT INTO main.demo.customer_array_json
VALUES (
    1001,
    '{
      "customer_id": 1001,
      "name": "Jan Jansen",
      "orders": [
        {
          "order_id": "ORD001",
          "amount": 125.50,
          "status": "COMPLETED"
        },
        {
          "order_id": "ORD002",
          "amount": 89.95,
          "status": "OPEN"
        }
      ]
    }'
);


Parse the JSON

We use from_json() again, but this time we define an ARRAY containing STRUCT elements.


SELECT
    from_json(
        payload,
        'STRUCT<
            customer_id: BIGINT,
            name: STRING,
            orders: ARRAY<
                STRUCT<
                    order_id: STRING,
                    amount: DOUBLE,
                    status: STRING
                >
            >
        >'
    ) AS customer

FROM main.demo.customer_array_json;

Now Spark understands that orders contains multiple order objects. 




Expand the ARRAY using EXPLODE


How do we turn the individual orders into separate rows? For this, we use EXPLODE().

SELECT
    customer.customer_id,
    customer.name,
    order.order_id,
    order.amount,
    order.status

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                name: STRING,
                orders: ARRAY<
                    STRUCT<
                        order_id: STRING,
                        amount: DOUBLE,
                        status: STRING
                    >
                >
            >'
        ) AS customer

    FROM main.demo.customer_array_json
) parsed

LATERAL VIEW EXPLODE(customer.orders) exploded AS order;

Resulting in : 




Notice what happened: one customer record became two rows because the customer has two orders. This is an important difference compared with STRUCT. A STRUCT extracts fields from an existing row, while EXPLODE expands an ARRAY into multiple rows.


Create a SQL View

We can make this transformation reusable by creating a view.


CREATE OR REPLACE VIEW main.demo.v_customer_orders AS

SELECT
    customer.customer_id,
    customer.name,
    order.order_id,
    order.amount,
    order.status

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                name: STRING,
                orders: ARRAY<
                    STRUCT<
                        order_id: STRING,
                        amount: DOUBLE,
                        status: STRING
                    >
                >
            >'
        ) AS customer

    FROM main.demo.customer_array_json
) parsed

LATERAL VIEW EXPLODE(customer.orders) exploded AS order;

Query the view:


SELECT *
FROM main.demo.v_customer_orders;

ARRAY is useful when a JSON document contains lists of repeating elements, such as:

  • Customer orders

  • Product items

  • Transaction lines

  • Event collections

  • API result lists

One important consideration: EXPLODE changes the granularity of the data. If one customer has five orders, the resulting dataset contains five rows for that customer.