Skip to main content
This topic describes how to leverage the database’ asynchronous materialized views to rewrite and accelerate queries.

Overview

The database’ asynchronous materialized view uses a widely adopted transparent query rewrite algorithm based on the SPJG (select-project-join-group-by) form. Without the need to modify the query statement, the database can automatically rewrite queries against the base tables into queries against the corresponding materialized view that contains the pre-computed results. As a result, materialized views can help you significantly reduce computational costs, and substantially accelerate query execution. The query rewrite feature based on asynchronous materialized views is particularly useful in the following scenarios:
  • Pre-aggregation of metrics You can use materialized views to create a pre-aggregated metric layer if you are dealing with a high dimensionality of data.
  • Joins of wide tables Materialized views allow you to transparently accelerate queries with joins of multiple large wide tables in complex scenarios.
  • Query acceleration in the data lake Building an external catalog-based materialized view can easily accelerate queries against data in your data lake.
    NOTE Asynchronous materialized views created on base tables in a JDBC catalog do not support query rewrite.

Features

The database’ asynchronous materialized view-based automatic query rewrite features the following attributes:
  • Strong data consistency: If the base tables are native tables, the database ensures that the results obtained through the materialized view-based query rewrite are consistent with the results returned from the direct query against the base tables.
  • Staleness rewrite: the database supports staleness rewrite, allowing you to tolerate a certain level of data expiration to cope with scenarios with frequent data changes.
  • Multi-table joins: the database’ asynchronous materialized view supports various types of joins, including some complex join scenarios like View Delta Joins and Derivable Joins, allowing you to accelerate queries in scenarios involving large wide tables.
  • Aggregation rewrite: the database can rewrite queries with aggregations to improve report performance.
  • Nested materialized view: the database supports rewriting complex queries based on nested materialized views, expanding the scope of queries that can be rewritten.
  • Union rewrite: You can combine the Union rewrite feature with the TTL (Time-to-Live) of the materialized view’s partitions to achieve the separation of the hot and cold data, which allows you to query hot data from materialized views and historical data from the base table.
  • Materialized views on views: You can accelerate the queries in scenarios with data modeling based on views.
  • Materialized views on external catalogs: You can accelerate queries in data lakes.
  • Complex expression rewrite: It can handle complex expressions, including function calls and arithmetic operations, catering to advanced analytical and calculation requirements.
These features will be elaborated in the following sections.

Join rewrite

The database supports rewriting queries with various types of joins, including Inner Join, Cross Join, Left Outer Join, Full Outer Join, Right Outer Join, Semi Join, and Anti Join. The following is an example of rewriting queries with joins. Create two base tables as follows:
With the above base tables, you can create a materialized view as follows:
Such a materialized view can rewrite the following query:
Rewrite-1 The database supports rewriting join queries with complex expressions, such as arithmetic operations, string functions, date functions, CASE WHEN expressions, and OR predicates. For example, the above materialized view can rewrite the following query:
In addition to the conventional scenario, the database further supports rewriting join queries in more complicated scenarios.

Query Delta Join rewrite

Query Delta Join refers to a scenario in which the tables joined in a query are a superset of the tables joined in a materialized view. For instance, consider the following query that involves joins of three tables: lineorder, customer, and part. If the materialized view join_mv1 contains only the join of lineorder and customer, the database can rewrite the query using join_mv1. Example:
Its original query plan and the one after the rewrite are as follows: Rewrite-2

View Delta Join rewrite

View Delta Join refers to a scenario in which the tables joined in a query are a subset of the tables joined in a materialized view. This feature is typically used in scenarios involving large wide tables. For example, in the context of the Star Schema Benchmark (SSB), you can create a materialized view that joins all tables to improve query performance. Through testing, it has been found that query performance for multi-table joins can achieve the same level of performance as querying the corresponding large wide table after transparently rewriting the queries through the materialized view. To perform a View Delta Join rewrite, the materialized view must contain the 1:1 cardinality preservation join that does not exist in the query. Here are the nine types of joins that are considered cardinality preservation joins, and satisfying any one of them enables View Delta Join rewriting: Rewrite-3 Take SSB tests as an example, create the following base tables:
Create the materialized view lineorder_flat_mv that joins lineorder, customer, supplier, part, and dates:
SSB Q2.1 involves joining four tables, but it lacks the customer table compared to the materialized view lineorder_flat_mv. In lineorder_flat_mv, lineorder INNER JOIN customer is essentially a cardinality preservation join. Therefore, logically, this join can be eliminated without affecting the query results. As a result, Q2.1 can be rewritten using lineorder_flat_mv. SSB Q2.1:
Its original query plan and the one after the rewrite are as follows: Rewrite-4 Similarly, other queries in the SSB can also be transparently rewritten using lineorder_flat_mv, thus optimizing query performance.

Join Derivability rewrite

Join Derivability refers to a scenario in which the join types in the materialized view and the query are not consistent, but the materialized view’s join results contain the results of the query’s join. Currently, it supports two scenarios - joining three or more tables, and joining two tables.
  • Scenario one: Joining three or more tables Suppose the materialized view contains a Left Outer Join between tables t1 and t2 and an Inner Join between tables t2 and t3. In both joins, the join condition includes columns from t2. The query, on the other hand, contains an Inner Join between t1 and t2, and an Inner Join between t2 and t3. In both joins, the join condition includes columns from t2. In this case, the query can be rewritten using the materialized view. This is because in the materialized view, the Left Outer Join is executed first, followed by the Inner Join. The right table generated by the Left Outer Join has no results for the matching (that is, columns in the right table are NULL). These results are subsequently filtered out during the Inner Join. Therefore, the logic of the materialized view and the query is equivalent, and the query can be rewritten. Example: Create the materialized view join_mv5:
    join_mv5 can rewrite the following query:
    Its original query plan and the one after the rewrite are as follows: Rewrite-5 Similarly, if the materialized view is defined as t1 INNER JOIN t2 INNER JOIN t3, and the query is LEFT OUTER JOIN t2 INNER JOIN t3, the query can also be rewritten. Furthermore, this rewriting capability extends to scenarios involving more than three tables.
  • Scenario two: Joining two tables The Join Derivability Rewrite feature involving two tables supports the following specific cases: Rewrite-6 In cases 1 to 9, filtering predicates must be added to the rewritten result to ensure semantic equivalence. For example, create a materialized view as follows:
    The following query can be rewritten using join_mv3, and the predicate c_custkey IS NOT NULL is added to the rewritten result:
    Its original query plan and the one after the rewrite are as follows: Rewrite-7 In case 10, the Left Outer Join query must include the filtering predicate IS NOT NULL in the right table, for example, =, <>, >, <, <=, >=, LIKE, IN, NOT LIKE, or NOT IN. For example, create a materialized view as follows:
    join_mv4 can rewrite the following query, where customer.c_address = "Sb4gxKs7" is the filtering predicate IS NOT NULL:
    Its original query plan and the one after the rewrite are as follows: Rewrite-8

Aggregation rewrite

The database’ asynchronous materialized view supports rewriting multi-table aggregate queries with all available aggregate functions, including bitmap_union, hll_union, and percentile_union. For example, create a materialized view as follows:
It can rewrite the following query:
Its original query plan and the one after the rewrite are as follows: Rewrite-9 The following sections expound on the scenarios where the Aggregation Rewrite feature can be useful.

Aggregation Rollup rewrite

The database supports rewriting queries with Aggregation Rollup, that is, the database can rewrite aggregate queries with a GROUP BY a clause using an asynchronous materialized view created with a GROUP BY a,b clause. For example, the following query can be rewritten using agg_mv1:
Its original query plan and the one after the rewrite are as follows: Rewrite-10
NOTE Currently, rewriting the grouping set, grouping set with rollup, or grouping set with cube is not supported.
Only certain aggregate functions support query rewrite with Aggregate Rollup. In the preceding example, if the materialized view order_agg_mv uses count(distinct client_id) instead of bitmap_union(to_bitmap(client_id)), the database cannot rewrite the queries with Aggregate Rollup. The following table shows the correspondence between the aggregate functions in the original query and the aggregate function used to build the materialized view. You can select the corresponding aggregate functions to build a materialized view according to your business scenario. DISTINCT aggregates without the corresponding GROUP BY column cannot be rewritten with Aggregate Rollup. However, from StarRocks v3.1 onwards, if a query with an Aggregate Rollup DISTINCT aggregate function does not have a GROUP BY column but an equal predicate, it can also be rewritten by the relevant materialized view because the database can convert the equal predicates into a GROUP BY constant expression. In the following example, the database can rewrite the query with the materialized view order_agg_mv1.
In addition to the above functions, starting from StarRocks v3.4.0, asynchronous materialized views also support generic aggregate functions which can also be used for query rewrite. For more information about generic aggregate functions, see Generic aggregate function states.

Aggregation pushdown

From v3.3.0, the database supports aggregation pushdown for materialized view query rewrite. When this feature is enabled, aggregate functions will be pushed down to the Scan Operator during query execution and rewritten by the materialized view before the Join Operator is executed. This will relieve the data expansion caused by Join and thereby improve the query performance. This feature is disabled by default, To enable this feature, you must set the system variable enable_materialized_view_agg_pushdown_rewrite to true. Suppose you want to accelerate the following SSB-based query SQL1:
SQL1 consists of aggregations on the table lineorder and a Join of lineorder and dates. Because aggregations happen within lineorder and the Join with dates is only used for data filtering, SQL1 is logically equivalent to the following SQL2:
SQL2 brings aggregations forward, thus shrinking the data size of Join. You can create a materialized view based on the sub-query of SQL2, and enable aggregation pushdown to rewrite and accelerate the aggregations:
Then, SQL1 will be rewritten and accelerated by the materialized view. It is rewritten to the following query:
Please note that only certain aggregate functions that support Aggregate Rollup rewrite are eligible for pushdown. They are:
  • MIN
  • MAX
  • COUNT
  • COUNT DISTINCT
  • SUM
  • BITMAP_UNION
  • HLL_UNION
  • PERCENTILE_UNION
  • BITMAP_AGG
  • ARRAY_AGG_DISTINCT
Note
  • After pushdown, the aggregate functions need to be rolled up to align with the original semantics. For more instructions on Aggregation Rollup, Please refer to Aggregation Rollup Rewrite.
  • Aggregation pushdown supports Rollup rewrite of Count Distinct based on Bitmap or HLL functions.
  • Aggregation pushdown only supports pushing aggregate functions down to the Scan Operator before Join, Filter, or Where operators.
  • Aggregation pushdown only supports query rewrite and acceleration based on materialized view built on a single table.

COUNT DISTINCT rewrite

The database supports rewriting COUNT DISTINCT calculations into bitmap-based calculations, enabling high-performance, precise deduplication using materialized views. For example, create a materialized view as follows:
It can rewrite the following query:

Nested materialized view rewrite

The database supports rewriting queries using nested materialized view. For example, create the materialized views join_mv2, agg_mv2, and agg_mv3 as follows:
Their relationship is as follows: Rewrite-11 agg_mv3 can rewrite the following query:
Its original query plan and the one after the rewrite are as follows: Rewrite-12

Union rewrite

Predicate Union rewrite

When the predicate scope of a materialized view is a subset of the predicate scope of a query, the query can be rewritten using a UNION operation. For example, create a materialized view as follows:
It can rewrite the following query:
Its original query plan and the one after the rewrite are as follows: Rewrite-13 In this context, agg_mv5 contains data where lo_orderkey < 300000000. Data where lo_orderkey >= 300000000 is directly obtained from the base table lineorder. Finally, these two sets of data are combined using a UNION operation and then aggregated to obtain the final result.

Partition Union rewrite

Suppose you created a partitioned materialized view based on a partitioned table. When the partition range that a rewritable query scanned is a superset of the most recent partition range of the materialized view, the query will be rewritten using a UNION operation. For example, consider the following materialized view agg_mv4. Its base table lineorder currently contains partitions from p1 to p7, and the materialized view also contains partitions from p1 to p7.
If a new partition p8, with a partition range of [("19990101"), ("20000101")), is added to lineorder, the following query can be rewritten using a UNION operation:
Its original query plan and the one after the rewrite are as follows: Rewrite-14 As shown above, agg_mv5 contains the data from partitions p1 to p7, and the data from partition p8 is directly queried from lineorder. Finally, these two sets of data are combined using a UNION operation.

View-based materialized view rewrite

From v3.1.0 onwards, the database supports creating materialized views based on views. Subsequent queries against the views can be rewritten if they are of the SPJG pattern. By default, queries against views are automatically transcribed into queries against the base tables of the views and then transparently matched and rewritten. However, in real-world scenarios, data analysts may perform data modeling upon complex, nested views, which cannot be directly transcribed. As a result, materialized views created based on such views cannot rewrite queries. To improve its capability in the preceding scenario, the database optimizes the view-based materialized view query rewrite logic from v3.3.0 onwards.

Fundamentals

In the previous query rewrite logic, the database will transcribe queries against a view into queries against the base tables of the view. Query rewrite will encounter failures if the execution plan of the transcribed query mismatches the SPJG pattern. To solve this problem, the database introduces a new operator - LogicalViewScanOperator, to simplify the structure of the execution plan tree without transcribing the query. This operator seeks to match the execution plan tree with the SPJG pattern, therefore facilitating query rewrite. The following example lists a query with an AGGREGATE sub-query, a view built upon the sub-query, the transcribed query based on the view, and the materialized view built upon the view:
The execution plan of the original query, as shown on the left of the following diagram, mismatches the SPJG pattern due to the LogicalAggregateOperator within the JOIN. The database does not support query rewrite for such cases. However, by defining a view based on the sub-query, the original query can be transcribed into a query against the view. With the LogicalViewScanOperator, the database can transfer the mismatched part into the SPJG pattern, therefore allowing query rewrite under this circumstance. img

Usage

View-based materialized view query rewrite is disabled by default. To enable this feature, you must set the following variable:

Use cases

Rewrite queries using single-view-based materialized views

The database supports rewriting queries with a materialized view built upon a single view, including queries with aggregations. For example, you can build the following view and materialized view for the TPC-H Query 18:
The materialized view can rewrite both the following queries:

Rewrite queries with JOIN using view-based materialized views

The database supports rewriting queries with JOINs between views or between views and tables, including aggregations upon JOINs. For example, you can create the following views and materialized view:
The materialized view can rewrite both the following queries:

Rewrite queries using materialized views built upon external table-based views

You can build views upon tables in external catalogs and then materialized views upon the views to rewrite queries. The usage is similar to that for internal tables.

External catalog-based materialized view rewrite

The database supports building asynchronous materialized views on Hive catalogs, Hudi catalogs, Iceberg catalogs, and Paimon catalogs, and transparently rewriting queries with them.

Text-based materialized view rewrite

From v3.3.0 onwards, the database supports text-based materialized view rewrite, which significantly extends its query rewrite capability.

Fundamentals

To achieve text-based materialized view rewrite, the database compares the abstract syntax tree of the query (or its sub-queries) with that of the materialized view’s definition. When they match each other, the database will rewrite the query based on the materialized view. Text-based materialized view rewrite is simple, efficient, and has fewer limitations than regular SPJG-type materialized view query rewrite. When used correctly, this feature can significantly accelerate query performance. Text-based materialized view rewrite is not limited to the SPJG-type operators. It also supports operators such as Union, Window, Order, Limit, and CTE.

Usage

Text-based materialized view rewrite is enabled by default. You can manually disable this feature by setting the variable enable_materialized_view_text_match_rewrite to false. The FE configuration item enable_materialized_view_text_based_rewrite controls whether to build the abstract syntax tree while creating an asynchronous materialized view. This feature is also enabled by default. Setting this item to false will disable text-based materialized view rewrite on the system level. The variable materialized_view_subquery_text_match_max_count controls the maximum number of times to compare the abstract syntax trees of the materialized view and the sub-queries. The default value is 4. Increasing this value will also increase the time consumption of the optimizer. Please note that, only when the materialized view meets the timeliness (data consistency) requirement can it be used for text-based query rewrite. You can manually set the consistency check rule using the property query_rewrite_consistency when creating the materialized view. For more information, see CREATE MATERIALIZED VIEW.

Use cases

Queries are eligible for text-based materialized view rewrite in the following scenarios:
  • The original query matches the definition of the materialized view.
  • The original query’s sub-query matches the definition of the materialized view.
Compared to the regular SPJG-type materialized view query rewrite, text-based materialized view rewrite supports more complex queries, for example, multi-layer aggregations. Info
  • It is recommended to encapsulate the query to match in the sub-query of the original query.
  • Please do not encapsulate ORDER BY clauses in the definition of the materialized view or the sub-query of the original query. Otherwise, the query cannot be rewritten because the ORDER BY clauses in the sub-query are eliminated by default.
For example, you can create the following materialized view:
The materialized view can rewrite both the following queries:
However, the materialized view cannot rewrite the following query because the original query contains an ORDER BY clause:

Configure query rewrite

You can configure the asynchronous materialized view query rewrite through the following session variables:

Check if a query is rewritten

You can check if your query is rewritten by viewing its query plan using the EXPLAIN statement. If the field TABLE under the section OlapScanNode shows the name of the corresponding materialized view, it means that the query has been rewritten based on the materialized view.

Disable query rewrite

By default, the database enables query rewrite for asynchronous materialized views created based on the default catalog. You can disable this feature by setting the session variable enable_materialized_view_rewrite to false. For asynchronous materialized views created based on an external catalog, you can disable this feature by setting the materialized view property force_external_table_query_rewrite to false using ALTER MATERIALIZED VIEW.

Limitations

In terms of materialized view query rewrite, the database currently has the following limitations:
  • The database does not support rewriting queries with non-deterministic functions, including rand, random, uuid, and sleep.
  • The database does not support rewriting queries with window functions.
  • Materialized views defined with statements containing LIMIT, ORDER BY, UNION, EXCEPT, INTERSECT, MINUS, GROUPING SETS, WITH CUBE, or WITH ROLLUP cannot be used for query rewrite.
  • Strong consistency of query results is not guaranteed between base tables and materialized views built on external catalogs.
  • Asynchronous materialized views created on base tables in a JDBC catalog do not support query rewrite.
In terms of view-based materialized view query rewrite, the database currently has the following limitations:
  • Currently, the database does not support Partition Union rewrite.
  • Query rewrite is not supported if the view contains random functions, including rand(), random(), uuid(), and sleep().
  • Query rewrite is not supported if the view contains columns with same names. You must assign different aliases for columns with the same names.
  • Views that are used to create a materialized view must contain at least one column of the following data types: integer types, date types, and string types. For example, you cannot create a materialized that queries the view, because total_cost is a DOUBLE-type column.