🚀
Introducing Versions: Develop data products using Git. Join the waitlist

ClickHouse Tips #4: Materializing UNION ALL queries

Learn how to materialize queries on ClickHouse when there are UNION ALL operations involved, and when you can use SimpleAggregateFunction instead of AggregateFunction.
Elena Torró
Software Developer
Mar 7, 2021
 ・ 
  min read

The problem

There are times when you have a query that involves {% code-line %}UNION ALL{% code-line-end %} statements and you’d like to materialize it. If you try to do it on ClickHouse, it will fail. The solution is to create two materialized views that write to the same table. In this post we’ll explain how to do it on ClickHouse and on Tinybird.

We’ll also use SimpleAggregateFunction(function, type). It is a data type that stores the value of the given aggregate function without storing the full state as {% code-line %}AggregateFunction{% code-line-end %} does. According to the documentation, “it can be applied to functions for which the following property holds: the result of applying a function f to a row set S1 UNION ALL S2 can be obtained by applying f to parts of the row set separately, and then again applying f to the results: f(S1 UNION ALL S2) = f(f(S1) UNION ALL f(S2))”. What does this mean?

Imagine that function is {% code-line %}sum{% code-line-end %}, one set is {% code-line %}[1, 3, 7]{% code-line-end %} and another set is {% code-line %}[2, 4, 6]{% code-line-end %}. Doing {% code-line %}sum(sum(1, 3, 7), sum(2, 4, 6)){% code-line-end %} will yield the same result as doing {% code-line %}sum(1, 3, 7, 2, 4, 6){% code-line-end %}. So if we want to use {% code-line %}sum{% code-line-end %} in a materialize view, we can store the result in a {% code-line %}SimpleAggregationFunction(sum, type){% code-line-end %} data type. Other functions where this happen are {% code-line %}any{% code-line-end %}, {% code-line %}anyLast{% code-line-end %}, {% code-line %}min{% code-line-end %}, {% code-line %}max{% code-line-end %}, and more.

Therefore, SimpleAggregateFunctions data types will be useful, for instance, when using a data source to store the results of two materialized views in order to perform the same output as doing an “UNION ALL” of two tables, but faster.

A practical example

Let’s see first an example of what we would like to achieve. In this example, we’ll be using Unsplash open data.

We have will be using two source tables: collections and keywords. The first one contains information about every time a photo has been added to a collection, and the second one about the keywords used to describe each photo.

Our purpose is to create an enpoint to get the last time a photo was added into a collection and some information about this collection along with the complete list of keywords for this photo. In order to explore the data and get an idea of what we want to accomplish, we will be doing something similar to the following aggregation over the result of an UNION ALL:

How can we achieve the same result but using materialized views? We can not materialize the result of an UNION ALL, but we can make use of the AggregatingMergeTree engine.

First of all, let’s create the destination table, photo_last_collected:

What should we take into account here:

  • Every {% code-line %}SimpleAggregateFunction{% code-line-end %} using {% code-line %}groupArrayArray{% code-line-end %} must have Array type, and can’t be {% code-line %}Nullable{% code-line-end %}. The {% code-line %}groupArray{% code-line-end %} function can’t contain null values.
  • We could also use {% code-line %}groupUniqArrayArray{% code-line-end %} in order to avoid duplicated keywords

Now, let’s create two materialized views, one per table. This view materializes the photo id and the keywords that belong to each photo to the photo_last_collected Data Source:

And the following view materializes the photo id, the last time it was added to a collection, the collection id and the collection title that belong to each photo to the photo_last_collected Data Source:

Key points:

  • As a rule of thumb, column names must have the same name and must be inserted in the same order into the destination Data Source
  • The {% code-line %}keywords_list{% code-line-end %} can not simply be an empty array, we must cast it correctly to {% code-line %}Array(String){% code-line-end %}, because that’s the data type of the destination column
  • {% code-line %}last_time_collected_at{% code-line-end %}, {% code-line %}collection_id{% code-line-end %} and {% code-line %}collection_title{% code-line-end %} can’t either be {% code-line %}Null{% code-line-end %}, we have to cast them to the exact type of the column in the landing Data Source they’re being saved in

If you create the Tinybird Data Sources and Pipe files under a project with this structure (the folder structure is already created when you do {% code-line %}tb init{% code-line-end %} with our CLI):

You’d just have to run {% code-line %}tb push --push-deps --populate --wait{% code-line-end %} to create the Data Source on Tinybird, the materialized views, and populate the Data Source.

Then, you’d only have to get the data already joined from the {% code-line %}photo_last_collected{% code-line-end %} destination table.

As you can see, the result is the same as from the first query, and it’s about 6x faster.

In Tinybird's Data Flow graph you can see how the collections and keywords photos are materialize data into the photo_last_collected Data Source
In Tinybird's Data Flow graph you can see how the collections and keywords photos are materialize data into the photo_last_collected Data Source

A similar result would have been obtained if we had used AggregateFunction when defining the {% code-line %}photo_last_collected{% code-line-end%} Data Source. Using SimpleAggregateFunction has several advantages:

  • As SimpleAggregateFunction just saves the value instead of the full state of its aggregate function (like AggregateFunction does), it’s more performant.
  • It lets us write the cleaner and simpler queries, as we don’t have to use the {% code-line %}-State{% code-line-end%} suffixes for the Materialized Views and we can just query the landing datasource doing {% code-line %}SELECT * FROM photo_last_collected{% code-line-end %}. Otherwise we’d have to use the {% code-line %}-Merge{% code-line-end %} suffix to merge the intermediate states of the aggregated columns.