Application scenarios
We recommend that you use the query cache in the following scenarios:- You frequently run aggregate queries on individual flat tables or on multiple joined tables that are connected in a star schema.
- Most of your aggregate queries are non-GROUP BY aggregate queries and low-cardinality GROUP BY aggregate queries.
- Your data is loaded in append mode by time partition and can be categorized as hot data and cold data based on access frequency.
-
The query engine is Pipeline. To enable the Pipeline engine, set the session variable
enable_pipeline_enginetotrue.NOTE Other query engines do not support the query cache.
- The queries are on native OLAP tables (from v2.5) or cloud-native tables (from v3.0). The query cache does not support queries on external tables. The query cache also supports queries whose plans require access to synchronous materialized views. However, the query cache does not support queries whose plans require access to asynchronous materialized views.
-
The queries are aggregate queries on individual tables or on multiple joined tables.
NOTE
- The query cache supports Broadcast Join and Bucket Shuffle Join.
- The query cache supports two tree structures that contain Join operators: Aggregation-Join and Join-Aggregation. Shuffle joins are not supported in the Aggregation-Join tree structure, while Hash joins are not supported in the Join-Aggregation tree structure.
-
The queries do not include nondeterminstic functions such as
rand,random,uuid, andsleep.
Feature boundaries
- The query cache is based on per-tablet computations of the Pipeline engine. Per-tablet computation means that a pipeline driver can process entire tablets one by one rather than processing a portion of a tablet or many tablets interleaved together. If the number of tablets that need to be processed by each individual BE for a query is greater than or equal to the number of pipeline drivers that are invoked to run this query, the query cache works. The number of pipeline drivers invoked represents the actual degree of parallelism (DOP). If the number of tablets is smaller than the number of pipeline drivers, each pipeline driver processes only a portion of a specific tablet. In this situation, per-tablet computation results cannot be produced, and therefore the query cache does not work.
- In the database, an aggregate query consists of at least four stages. Per-Tablet computation results generated by AggregateNode in the first stage can be cached only when OlapScanNode and AggregateNode compute data from the same fragment. Per-Tablet computation results generated by AggregateNode in the other stages cannot be cached. For some DISTINCT aggregate queries, if the session variable
cbo_cte_reuseis set totrue, the query cache does not work when OlapScanNode, which produces data, and the stage-1 AggregateNode, which consumes the produced data, compute data from different fragments and are bridged by an ExchangeNode. The following two examples show scenarios in which CTE optimizations are performed and therefore the query cache does not work:- The output columns are computed by using the aggregate function
avg(distinct). - The output columns are computed by multiple DISTINCT aggregate functions.
- The output columns are computed by using the aggregate function
- If your data is shuffled before aggregation, the query cache cannot accelerate the queries on that data.
- If the group-by columns or deduplicating columns of a table are high-cardinality columns, large results will be generated for aggregate queries on that table. In these cases, the queries will bypass the query cache at runtime.
- The query cache occupies a small amount of memory provided by the BE to save computation results. The size of the query cache defaults to 512 MB. Therefore, it is unsuitable for the query cache to save large-sized data items. Additionally, after you enable the query cache, query performance is decreased if the cache hit ratio is low. Therefore, if the size of computation results generated for a tablet exceeds the threshold specified by the
query_cache_entry_max_bytesorquery_cache_entry_max_rowsparameter, the query cache no longer works for the query and the query is switched to Passthrough mode.
How it works
When the query cache is enabled, each BE splits the local aggregation of a query into the following two stages:- Per-tablet aggregation The BE processes each tablet individually. When the BE begins processing a tablet, it first probes the query cache to see if the intermediate result of aggregation on that tablet is in the query cache. If so (a cache hit), the BE directly fetches the intermediate result from the query cache. If no (a cache miss), the BE accesses the data on disk and performs local aggregation to compute the intermediate result. When the BE finished processing a tablet, it populates the query cache with the intermediate result of aggregation on that tablet.
-
Inter-tablet aggregation
The BE gathers the intermediate results from all tablets involved in the query and merges them into a final result.


query_cache_capacity), the least recently used cache entries are evicted out of the query cache.
NOTE In the future, the database will also support a Time to Live (TTL)-based eviction policy based on which cache entries can be evicted out of the query cache.The FE determines whether each query needs to be accelerated by using the query cache and normalizes the queries to eliminate trivial literal details that have no effect on the semantics of queries. To prevent the performance penalty incurred by the bad cases of the query cache, the BE adopts an adaptive policy to bypass the query cache at runtime.
Enable query cache
This section describes the parameters and session variables that are used to enable and configure the query cache.FE session variables
BE parameters
You need to configure the following parameter in the BE configuration file be.conf. After you reconfigure this parameter for a BE, you must restart the BE to make the new parameter setting take effect.Engineered for maximum cache hit rate in all scenarios
Consider three scenarios where the query cache is still effective even when the queries are not identical literally. These three scenarios are:- Semantically equivalent queries
- Queries with overlapping scanned partitions
- Queries against data with append-only data changes (no UPDATE or DELETE operations)
Semantically equivalent queries
When two queries are similar, which does not mean that they must be literally equivalent but means that they contain semantically equivalent snippets in their execution plans, they are considered semantically equivalent and can reuse each other’s computation results. In a broad sense, two queries are semantically equivalent if they query data from the same source, use the same computation method, and have the same execution plan. The database applies the following rules to evaluate whether two queries are semantically equivalent:-
If the two queries contain multiple aggregations, they are evaluated as semantically equivalent as long as their first aggregations are semantically equivalent. For example, the following two queries, Q1 and Q2, both contain multiple aggregations, but their first aggregations are semantically equivalent. Therefore, Q1 and Q2 are evaluated as semantically equivalent.
-
Q1
-
Q2
-
Q1
-
If the two queries both belong to one of the following query types, they can be evaluated as semantically equivalent. Note that queries that include a HAVING clause cannot be evaluated as semantically equivalent to queries that do not include a HAVING clause. However, the inclusion of an ORDER BY or LIMIT clause does not affect the evaluation of whether two queries are semantically equivalent.
-
GROUP BY aggregations
NOTE In the preceding example, the HAVING clause is optional.
-
GROUP BY DISTINCT aggregations
NOTE In the preceding example, the HAVING clause is optional.
-
Non-GROUP BY aggregations
-
Non-GROUP BY DISTINCT aggregations
-
GROUP BY aggregations
-
If either query includes
PartitionColumnRangePredicate,PartitionColumnRangePredicateis removed before the two queries are evaluated for semantic equivalence.PartitionColumnRangePredicatespecifies one of the following types of predicates that reference a partitioning column:col between v1 and v2: The values of the partitioning column fall within the [v1, v2] range, in whichv1andv2are constant expressions.v1 < col and col < v2: The values of the partitioning column fall within the (v1, v2) range, in whichv1andv2are constant expressions.v1 < col and col <= v2: The values of the partitioning column fall within the (v1, v2] range, in whichv1andv2are constant expressions.v1 <= col and col < v2: The values of the partitioning column fall within the [v1, v2) range, in whichv1andv2are constant expressions.v1 <= col and col <= v2: The values of the partitioning column fall within the [v1, v2] range, in whichv1andv2are constant expressions.
- If the output columns of the SELECT clauses of the two queries are the same after they are rearranged, the two queries are evaluated as semantically equivalent.
- If the output columns of the GROUP BY clauses of the two queries are the same after they are rearranged, the two queries are evaluated as semantically equivalent.
-
If the remaining predicates of the WHERE clauses of the two queries are semantically equivalent after
PartitionColumnRangePredicateis removed, the two queries are evaluated as semantically equivalent. - If the predicates in the HAVING clauses of the two queries are semantically equivalent, the two queries are evaluated as semantically equivalent.
lineorder_flat as an example:
lineorder_flat are semantically equivalent after they are processed as follows:
- Rearrange the output columns of the SELECT statement.
- Rearrange the output columns of the GROUP BY clause.
- Remove the output columns of the ORDER BY clause.
- Rearrange the predicates in the WHERE clause.
- Add
PartitionColumnRangePredicate.
-
Q1
-
Q2
cast expressions are removed during query optimizations. Therefore, these expressions do not impact the evaluation for semantic equivalence. Thirdly, the aliases of columns and relations do not impact the evaluation for semantic equivalence either.
Queries with overlapping scanned partitions
Query Cache supports predicate-based query splitting. Splitting queries based on predicate semantics help implement reuse of partial computation results. When a query contains a predicate that references the partitioning column of a table and the predicate specifies a value range, the database can split the range into multiple intervals based on table partitioning. The computation results from each individual interval can be separately reused by other queries. Use the following tablet0 as an example:
t0 is partitioned by day, and the column ts is the table’s partitioning column. Among the following four queries, Q2, Q3, and Q4 can reuse portions of the computation results cached for Q1:
-
Q1
The value range specified by the predicate
ts between '2022-01-02 12:30:00' and '2022-01-14 23:59:59'of Q1 can be split into the following intervals: -
Q2
Q2 can reuse the computation results within the following intervals of Q1:
-
Q3
Q3 can reuse the computation results within the following intervals of Q1:
-
Q4
Q4 can reuse the computation results within the following intervals of Q1:
Queries against data with append-only data changes
Query Cache supports multi-version caching. As data loads are made, new versions of tablets are generated. Consequently, the cached computation results that are generated from the previous versions of the tablets become stale and lag behind the latest tablet versions. In this situation, the multi-version caching mechanism tries to merge the stale results saved in the query cache and the incremental versions of the tablets stored on disk into the final results of the tablets so that new queries can carry the latest tablet versions. Multi-version caching is constrained by table types, query types, and data update types. The support for multi-version caching varies depending on table types and query types, as described in the following table.
The impact of data update types on multi-version caching is as follows:
- Data deletions Multi-version caching cannot work if incremental versions of tablets contain delete operations.
-
Data insertions
- If an empty version is generated for a tablet, the existing data of the tablet in the query cache remains valid and can still be retrieved.
- If a non-empty version is generated for a tablet, the existing data of the tablet in the query cache remains valid, but its version lags behind the latest version of the tablet. In this situation, the database reads the incremental data generated from the version of the existing data to the latest version of the tablet, merges the existing data with the incremental data, and populates the merged data into the query cache.
- Schema changes and tablet truncations If the schema of a table is changed or specific tablets of the table are truncated, new tablets are generated for the table. As a result, the existing data of the tablets of the table in the query cache becomes invalid.
Metrics
The profiles of queries for which the query cache works containCacheOperator statistics.
In the source plan of a query, if the pipeline contains OlapScanOperator, the names of OlapScanOperator and aggregate operators are prefixed with ML_ to denote that the pipeline uses MultilaneOperator to perform per-tablet computations. CacheOperator is inserted preceding ML_CONJUGATE_AGGREGATE to process the logic that controls how the query cache runs in Passthrough, Populate, and Probe modes. The profile of the query contains the following CacheOperator metrics that help you understand the query cache usage.
CachePopulateXXX metrics provide statistics about query cache misses for which the query cache is updated.
CachePassthroughXXX metrics provide statistics about query cache misses for which the query cache is not updated because the size of per-tablet computation results generated is large.
CacheProbeXXX metrics provide statistics about query cache hits.
In the multi-version caching mechanism, CachePopulate metrics and CacheProbe metrics may contain the same tablet statistics, and CachePassthrough metrics and CacheProbe metrics may also contain the same tablet statistics. For example, when the database computes the data of each tablet, it hits the computation results generated on the historical version of the tablet. In this situation, the database reads the incremental data generated from the historical version to the latest version of the tablet, computes the data, and merges the incremental data with the cached data. If the size of the computation results generated after the merging does not exceed the threshold specified by the query_cache_entry_max_bytes or query_cache_entry_max_rows parameter, the statistics of the tablet are collected into CachePopulate metrics. Otherwise, the statistics of the tablet are collected into CachePassthrough metrics.
RESTful API operations
-
metrics |grep query_cacheThis API operation is used to query the metrics related to the query cache. -
api/query_cache/statThis API operation is used to query the usage of the query cache. -
api/query_cache/invalidate_allThis API operation is used to clear the query cache.
be_host: the IP address of the node on which the BE resides.be_http_port: the HTTP port number of the node on which the BE resides.
Precautions
- The database needs to populate the query cache with the computation results of queries that are initiated for the first time. As a result, the query performance may be slightly lower than expected, and the query latency is increased.
- If you configure a large query cache size, the amount of memory that can be provisioned to query evaluation on the BE is decreased. We recommend that the query cache size do not exceed 1/6 of the memory capacity provisioned to query evaluation.
- If the number of tablets that need to be processed is smaller than the value of
pipeline_dop, the query cache does not work. To enable the query cache to work, you can setpipeline_dopto a smaller value such as1. From v3.0 onwards, the database adaptively adjusts this parameter based on query parallelism.
Examples
Dataset
-
Log in to your cluster, go to the destination database, and run the following command to create a table named
t0: -
Insert the following data records into
t0:
Query examples
The statistics of query cache-related metrics in this section are examples and are for reference only.Query cache works for local aggregations at stage 1
This includes three situations:- The query accesses only a single tablet.
- The query accesses multiple tablets from multiple partitions of a table that itself comprises a colocated group, and data does not need to be shuffled for aggregations.
- The query accesses multiple tablets from the same partition of a table, and data does not need to be shuffled for aggregations.

Query cache does not work for remote aggregations at stage 1
When aggregations on multiple tablets are forcibly performed at stage 1, data is first shuffled and then aggregated. Query example:Query cache works for local aggregations at stage 2
This includes three situations:- The aggregations at stage 2 of the query are compiled to compare the same type of data. The first aggregation is a local aggregation. After the first aggregation is complete, the results generated from the first aggregation are computed to perform a second aggregation, which is a global aggregation.
- The query is a SELECT DISTINCT query.
- The query includes one of the following DISTINCT aggregate functions:
sum(distinct),count(distinct), andavg(distinct). In most cases, aggregations are performed at stage 3 or 4 for such a query. However, you can runset new_planner_agg_stage = 1to forcibly perform aggregations at stage 2 for the query. If the query containsavg(distinct)and you want to perform aggregations at stage, you also need to runset cbo_cte_reuse = falseto disable CTE optimizations.

Query cache works for local aggregations at stage 3
The query is a GROUP BY aggregate query that includes a single DISTINCT aggregate function. The supported DISTINCT aggregate functions aresum(distinct), count(distinct), and avg(distinct).
NOTICE If the query includesQuery example:avg(distinct), you also need to runset cbo_cte_reuse = falseto disable CTE optimizations.

Query cache works for local aggregations at stage 4
The query is a non-GROUP BY aggregate query that includes a single DISTINCT aggregate function. Such queries include classical queries that remove deduplicate data. Query example:
Cached results are reused for two queries whose first aggregations are semantically equivalent
Use the following two queries, Q1 and Q2, as an example. Q1 and Q2 both include multiple aggregations, but their first aggregations are semantically equivalent. Therefore, Q1 and Q2 are evaluated as semantically equivalent, and can reuse each other’s computation results saved in the query cache.-
Q1
-
Q2
CachePopulate metrics for Q1.

CacheProbe metrics for Q2.

Query cache does not work for DISTINCT queries for which CTE optimizations are enabled
After you runset cbo_cte_reuse = true to enable CTE optimizations, the computation results for specific queries that include DISTINCT aggregate functions cannot be cached. A few examples are as follows:
-
The query contains a single DISTINCT aggregate function
avg(distinct):

-
The query contains multiple DISTINCT aggregate functions that reference the same column:

-
The query contains multiple DISTINCT aggregate functions that each reference a different column:

Best practices
When you create your table, specify a reasonable partition description and a reasonable distribution method, including:- Choose a single DATE-type column as the partition column. If the table contains more than one DATE-type column, choose the column whose values roll forward as data is incrementally ingested and that is used to define your interesting time ranges of queries.
- Choose a proper partition width. The data ingested most recently may modify the latest partitions of the table. Therefore, the cache entries involving the latest partitions are unstable and are apt to be invalidated.
- Specify a bucket number that is several dozen in the distribution description of the table creation statement. If the bucket number is exceedingly small, the query cache cannot take effect when the number of tablets that need to be processed by the BE is less than the value of
pipeline_dop.