Query hierarchical data

This article goes over how to query hierarchical data using SQL in Upsolver.

Transform with SQL enables to query hierarchical data.

For the following examples, we will assume that three events stream into the data source Purchases over time:

{ 
    "purchase_id": 1, "customer_id": 1, 
    "products": 
    [ 
        { "name": "Orange", "quantity": 3, "unit_price": 0.25 }, 
        { "name": "Banana", "quantity": 4, "price": 0.1 } 
    ] 
}
{ 
    "purchase_id": 2, "customer_id": 1, 
    "products": 
    [ 
        { "name": "Apple", "quantity": 1, "unit_price": 0.5 } 
    ] 
}
{ 
    "purchase_id": 1, "customer_id": 1, 
    "products": 
    [ 
        { "name": "Orange", "quantity": -2, "unit_price": 0.25 } 
    ] 
}

Using nested fields in GROUP BY statement:

With Transform with SQL, accessing nested fields in hierarchical data is simple and intuitive.

Fields in nested records can be accessed using the dot syntax. If a field is in an array, we use square braces [] to denote that.

Let’s have a look at the following query:

The result would be be:

customer_id

product_name

total_cost

1

"Orange"

0.25

1

"Banana"

0.4

1

"Apple"

0.5

Calculations on hierarchical data:

When doing calculations on hierarchical data, the result is placed back in the nested hierarchy. This "target location" affects how an operation works when dealing with arrays.

Example 1

The following query:

Results in the following output:

circle-info

Note: total_cost resulted in an array but number_of_purchased_products didn't. This is because some operations like SUM_VALUE return a single value, regardless of how many inputs they have.

Inline operations use the deepest possible location in the nesting as their target location.

Example 2

Results in the following data:

Example 3

The following query:

Results in the following data:

Example 4

The following query:

Results in the following data:

Last updated

Was this helpful?