NOTE
- After the data distribution is specified at table creation and query patterns or data characteristics in the business scenario evolves, since v3.2 the database supports modifying certain data distribution-related properties after table creation to meet the requirements for query performance in the latest business scenarios.
- Since v3.1, you do not need to specify the bucketing key in the DISTRIBUTED BY clause when creating a table or adding a partition. The database supports random bucketing, which randomly distributes data across all buckets. For more information, see Random bucketing.
- Since v2.5.7, you can choose not to manually set the number of buckets when you create a table or add a partition. The database can automatically set the number of buckets (BUCKETS). However, if the performance does not meet your expectations after the database automatically sets the number of buckets, and you are familiar with the bucketing mechanism, you can still manually set the number of buckets.
Introduction
Distribution methods in general
Modern distributed database systems generally use the following basic distribution methods: Round-Robin, Range, List, and Hash.
- Round-Robin: distributes data across different nodes in a cyclic.
- Range: distributes data across different nodes based on the ranges of partitioning column values. As shown in the diagram, the ranges [1-3] and [4-6] correspond to different nodes.
- List: distributes data across different nodes based on the discrete values of partitioning columns, such as gender and province. Each discrete value is mapped to a node, and multiple different values might be mapped to the same node.
- Hash: distributes data across different nodes based on a hash function.
Distribution methods in the database
The database supports both separate and composite use of data distribution methods.NOTE In addition to the general distribution methods, the database also supports Random distribution to simplify bucketing configuration.Also, the database distributes data by implementing the two-level partitioning + bucketing method.
- The first level is partitioning: Data within a table can be partitioned. Supported partitioning methods are expression partitioning, range partitioning, and list partitioning. Or you can choose not to use partitioning (the entire table is regarded as one partition).
- The second level is bucketing: Data in a partition needs to be further distributed into smaller buckets. Supported bucketing methods are hash and random bucketing.
-
Random distribution
If you do not configure partitioning and bucketing methods at table creation, random distribution is used by default. This distribution method currently can only be used to create a Duplicate Key table.
Note In shared-data mode, if you specify an explicit key type or an
ORDER BYclause but noDISTRIBUTED BYclause, range distribution is used by default instead. See Range-based bucketing. -
Hash distribution
-
Range distribution
From v4.1 onwards, the database supports the Range-based Distribution semantic, controlled by the FE configuration
enable_range_distribution. The data will be sequenced according to the data range of the key columns, and each tablet contains the data from a certain range. Note In shared-data mode, range distribution is enabled by default, controlled by the FE configurationenable_range_distribution; set it tofalseto disable this default. This configuration has no effect in shared-nothing mode. -
Range+Random distribution (This distribution method currently can only be used to create a Duplicate Key table.)
-
Range+Hash distribution
-
List+Random distribution (This distribution method currently can only be used to create a Duplicate Key table.)
-
List+Hash distribution
Partitioning
The partitioning method divides a table into multiple partitions. Partitioning primarily is used to split a table into different management units (partitions) based on the partitioning key. You can set a storage strategy for each partition, including the number of buckets, the strategy of storing hot and cold data, the type of storage medium, and the number of replicas. The database allows you to use different types of storage mediums within a cluster. For example, you can store the latest data on solid-state drives (SSDs) to improve query performance, and historical data on SATA hard drives to reduce storage costs.How to choose partitioning columns and granularity
- The partitioning key is composed of one or more partitioning columns. Selecting a proper partitioning column can effectively reduce the amount of data scanned during queries. In most business systems, partitioning based on time is commonly adopted to resolve certain issues caused by the deletion of expired data and facilitate the management of tiered storage of hot and cold data. In this case, you can use expression partitioning or range partitioning and specify a time column as the partitioning column. Additionally, if the data is frequently queried and managed based on ENUM values, you can use expression partitioning or list partitioning and specify a column including these values as the partitioning column.
- When choosing the partitioning granularity, you need to consider data volume, query patterns, and data management granularity.
- Example 1: If the monthly data volume in a table is small, partitioning by month can reduce the amount of metadata compared to partitioning by day, thereby reducing the resource consumption of metadata management and scheduling.
- Example 2: If the monthly data volume in a table is large and queries mostly request data of certain days, partitioning by day can effectively reduce the amount of data scanned during queries.
- Example 3: If the data needs to expire on a daily basis, partitioning by day is recommended.
Bucketing
The bucketing method divides a partition into multiple buckets. Data in a bucket is referred to as a tablet. The supported bucketing methods are random bucketing (from v3.1), hash bucketing, and range-based bucketing (from v4.1).- Random bucketing: When creating a table or adding partitions, you do not need to set a bucketing key. Data within a partition is randomly distributed into different buckets.
- Hash Bucketing: When creating a table or adding partitions, you need to specify a bucketing key. Data within the same partition is divided into buckets based on the values of the bucketing key, and rows with the same value in the bucketing key are distributed to the corresponding and unique bucket.
-
Range-based bucketing: From v4.1, if the FE configuration
enable_range_distributionis enabled, a table that specifies an explicit key type or anORDER BYclause but noDISTRIBUTED BYclause distributes data within a partition by the range of those columns. Tablets can be automatically split or merged to mitigate data skew. In shared-data mode this is enabled by default; setenable_range_distributiontofalseto disable it. The configuration has no effect in shared-nothing mode.
Create and manage partitions
Create partitions
Expression partitioning (recommended)
NOTICE The database’s shared-data mode supports the time function expression from v3.1.0 and the column expression from v3.1.1.Since v3.0, the database has supported expression partitioning (previously known as automatic partitioning) which is more flexible and easy to use. This partitioning method is suitable for most scenarios such as querying and managing data based on continuous date ranges or ENUM values. You only need to configure a partition expression at table creation, and the database will automatically create partitions during data loading. You no longer need to manually create numerous partitions in advance, nor configure dynamic partition properties. From v3.4 onwards, expression partitioning is further optimized to unify all partitioning strategies and supported more complex solutions. It is recommended in most cases, and will replace the other partitioning strategies in future releases. Example 1: Use a simple time function expression with a DATETIME column.
Range partitioning
Range partitioning is suitable for storing simple contiguous data, such as time series data, or continuous numerical data.Manually create partitions
Define the mapping relationship between each partition and the range of partitioning column values.-
The partitioning column is of date type.
-
The partitioning column is of integer type.
- Three specific time functions can be used as partitioning columns (supported since v3.3.0). When explicitly defining the mapping relationship between partitions and the ranges of partition column values, you can use a specific time function to convert the partition column values of timestamps or strings into date values, and then divide the partitions based on the converted date values.
Dynamic partitioning
Dynamic partitioning related properties are configured at table creation. The database automatically creates new partitions in advance and removes expired partitions to ensure data freshness, which implements time-to-live (TTL) management for partitions. Different from the automatic partition creation ability provided by the expression partitioning, dynamic partitioning can only periodically create new partitions based on the properties. If the new data does not belong to these partitions, an error is returned for the load job. However, the automatic partition creation ability provided by the expression partitioning can always create corresponding new partitions based on the loaded data.Create multiple partitions in batch
Multiple partitions can be created in batch at and after table creation. You can specify the start and end time for all the partitions created in batch inSTART() and END() and the partition increment value in EVERY(). However, note that the range of partitions is left-closed and right-open, which includes the start time but does not include the end time. The naming rule for partitions is the same as that of dynamic partitioning.
-
The partitioning column is of date type.
When the partitioning column is of date type, at table creation, you can use
START()andEND()to specify the start date and end date for all the partitions created in batch, andEVERY(INTERVAL xxx)to specify the incremental interval between two partitions. Currently, the interval granularity supportsHOUR(since v3.0),DAY,WEEK,MONTH, andYEAR.
2021-01-01 and end on 2021-01-04, with a partition increment of one day:
PARTITION BY clause in the CREATE TABLE statement:
EVERY for each batch of partitions (make sure that the partition ranges between different batches do not overlap). Partitions in each batch are created according to the START (xxx) END (xxx) EVERY (xxx) clause. For example:
PARTITION BY clause in the CREATE TABLE statement:
-
The partitioning column is of integer type.
When the data type of the partitioning column is INT, you specify the range of partitions in
STARTandENDand define the incremental value inEVERY. Example:NOTE The partitioning column values in START() and END() need to be wrapped in double quotation marks, while the incremental value in the EVERY() does not need to be wrapped in double quotation marks.
1 and ends at 5, with a partition increment of 1:
PARTITION BY clause in the CREATE TABLE statement:
EVERY for each batch of partitions (make sure that the partition ranges between different batches do not overlap). Partitions in each batch are created according to the START (xxx) END (xxx) EVERY (xxx) clause. For example:
- Three specific time functions can be used as partitioning columns (supported since v3.3.0). When explicitly defining the mapping relationship between partitions and the ranges of partition column values, you can use a specific time function to convert the partition column values of timestamps or strings into date values, and then divide the partitions based on the converted date values.
List partitioning (since v3.1)
List Partitioning is suitable for accelerating queries and efficiently managing data based on enum values. It is especially useful for scenarios where a partition needs to include data with different values in a partitioning column. For example, if you frequently query and manage data based on countries and cities, you can use this partitioning method and select thecity column as the partitioning column. In this case, one partition can contain data for various cities belonging to one country.
The database stores data in the corresponding partitions based on the explicit mapping of the predefined value list for each partition.
Manage partitions
Add partitions
For range partitioning and list partitioning, you can manually add new partitions to store new data. However for expression partitioning, because partitions are created automatically during data loading, you do not need to do so. The following statement adds a new partition to tablesite_access to store data for a new month:
Delete a partition
The following statement deletes partitionp1 from table site_access.
NOTE This operation does not immediately delete data in a partition. Data is retained in the Trash for a period of time (one day by default). If a partition is mistakenly deleted, you can use the RECOVER command to restore the partition and its data.
Restore a partition
The following statement restores partitionp1 and its data to table site_access.
View partitions
The following statement returns details of all partitions in tablesite_access.
Configure bucketing
Random bucketing (since v3.1)
The database distributes the data in a partition randomly across all buckets. It is suitable for scenarios with small data sizes and relatively low requirements for query performance. If you do not set a bucketing method, the database uses random bucketing by default and automatically sets the number of buckets. In shared-data mode, a table that specifies a key type or anORDER BY clause but no DISTRIBUTED BY clause uses range-based bucketing by default instead; see Range-based bucketing.
However, note that if you query massive amounts of data and frequently use certain columns as filter conditions, the query performance provided by random bucketing may not be optimal. In such scenarios, it is recommended to use hash bucketing. When these columns are used as filter conditions for queries, only data in a small number of buckets that the query hits need to be scanned and computed, which can significantly improve query performance.
Limits
- You can only use random bucketing to create a Duplicate Key table.
- You cannot specify a table bucketed randomly to belong to a Colocation Group.
- Spark Load cannot be used to load data into tables bucketed randomly.
DISTRIBUTED BY xxx statement is not used, so the database uses random bucketing by default, and automatically sets the number of buckets.
Hash bucketing
The database can use hash bucketing to subdivide data in a partition into buckets based on the bucketing key and the number of buckets. In hash bucketing, a hash function takes data’s bucketing key value as an input and calculates a hash value. Data is stored in the corresponding bucket based on the mapping between the hash values and buckets.Advantages
- Improved query performance: Rows with the same bucketing key values are stored in the same bucket, reducing the amount of data scanned during queries.
- Even data distribution: By selecting columns with higher cardinality (a larger number of unique values) as the bucketing key, data can be more evenly distributed across buckets.
How to choose the bucketing columns
We recommend that you choose the column that satisfies the following two requirements as the bucketing column.- high cardinality column such as ID
- column that often used in a filter for queries
- If the query is complex, it is recommended that you select high cardinality columns as bucketing columns to ensure that the data is as evenly distributed as possible across all the buckets and improve the cluster resource utilization.
- If the query is relatively simple, it is recommended to select columns that are frequently used as filer conditions in queries as bucketing columns to improve query efficiency.
Precautions
- When a table is created, you must specify the bucketing columns.
- The data types of bucketing columns must be INTEGER, DECIMAL, DATE/DATETIME, or CHAR/VARCHAR/STRING.
- Since 3.2, bucketing columns can be modified by using ALTER TABLE after table creation.
Examples
In the following example, thesite_access table is created by using site_id as the bucketing column. Additionally, when data in the site_access table is queried, data is often filtered by sites. Using site_id as the bucketing key can prune a significant number of irrelevant buckets during queries.
site_access has 10 buckets. In the following query, 9 out of 10 buckets are pruned, so the database only needs to scan 1/10 of the data in the site_access table:
site_id is unevenly distributed and a large number of queries only request data of a few sites, using only one bucketing column can result in severe data skew, causing system performance bottlenecks. In this case, you can use a combination of bucketing columns. For example, the following statement uses site_id and city_code as bucketing columns.
site_id is highly beneficial for short queries as it reduces data exchange between nodes, thereby enhancing the overall performance of the cluster. On the other hand, adopting two bucketing columns site_id and city_code is advantageous for long queries as it can leverage the overall concurrency of the distributed cluster to significantly improve performance.
NOTE
- Short queries involve scanning a small amount of data, and can be completed on a single node.
- Long queries involve scanning a large amount of data, and their performance can be significantly improved by parallel scanning across multiple nodes in a distributed cluster.
Range-based bucketing
From v4.1 onwards, the database supports the Range-based Distribution semantic, controlled by the FE configurationenable_range_distribution. In shared-data clusters, it is enabled by default. Range-based Distribution semantic addresses the performance issue for small-tenant, customer-facing scenarios, and allows an adaptive mechanism for handling data skew. The data will be sequenced according to the data range of the key columns, and each tablet contains the data from a certain range. For existing tables, you can split or merge tablets to achieve dynamic management of tablet size. Colocate Join is supported when creating a table with Range-based Distribution semantic.
The range-based distribution semantic is different from the default semantic in the following aspects:
- If the key type (AGGREGATE KEY/UNIQUE KEY/PRIMARY KEY/DUPLICATE KEY) is explicitly specified, and a DISTRIBUTED BY clause is not specified, the data will be distributed by range by default.
- If none of the key type, a DISTRIBUTED BY clause, or an ORDER BY is specified, a Duplicate Key table with the random bucketing strategy will be created.
- If the key type and a DISTRIBUTED BY clause are not specified, but an ORDER BY clause is specified, a Duplicate Key table with the range-based distribution strategy will be created. In this case, DUPLICATE KEY is equivalent to an ORDER BY clause, and vice versa.
- If both DUPLICATE KEY and an ORDER BY clause are specified, only the ORDER BY clause will take effect, and DUPLICATE KEY will be ignored.
- When the
colocate_withproperty is specified, you must also specify the colocated columns in addition to the colocation group. The colocated columns must be a prefix of the sort columns, and the default colocated columns are the sort columns.
Advantages
Fewer concepts and simpler usage- In most cases, table creation should require only column definitions and an
ORDER BYclause. - Users do not have to define a
DISTRIBUTED BYclause.
- Tablets support automatic splitting and merging, enabling the system to re-balance data dynamically and mitigate skew. For more instructions on splitting and merging tablets, see ALTER TABLE - Split or merge tablets.
- Data from a small tenant can be located on a single BE/CN for optimal locality.
- Data from a large tenant can be distributed across multiple BEs/CNs to maintain scalability and performance.
- Time-based partitioning is no longer a must for data management.
- A single partition will be capable of storing large data volumes, and the amount of data in different partitions can vary greatly, allowing users to choose partitioning strategies based on their specific needs.
Precautions
- This semantic is supported from v4.1 onwards. In shared-data mode it is enabled by default, controlled by the FE configuration
enable_range_distribution. - To disable it and fall back to the previous default distribution, set the FE configuration
enable_range_distributiontofalse. It has no effect in shared-nothing mode.
Target tablet size
Automatic tablet split and merge keep the tablets of a range-distributed table around a target size. By default, every table uses the FE configurationtablet_reshard_target_size (Default: 10 GB). To give a table its own target size, set the table property tablet_reshard_target_size (Unit: bytes) to a positive integer when you create the table, or change it with ALTER TABLE ... SET. The table property has the same name as the FE configuration and is supported only on range-distributed tables. On any other table, the statement fails with tablet_reshard_target_size is only supported for range-distributed tables.
- Automatic split splits a tablet once it reaches 1.5 times the property value (rounded up), into tablets of about the property value.
- Automatic merge, when enabled by the FE configuration
tablet_reshard_enable_tablet_merge, is triggered when two adjacent tablets together are smaller than 80% of the property value (rounded up), and the total size of each group of merged tablets does not exceed the property value. ALTER TABLE ... SPLIT TABLETandALTER TABLE ... MERGE TABLETuse the property value as the target size unlesstablet_reshard_target_sizeis specified in thePROPERTIESof the statement.- Tablet pre-split during data loading, online sort key changes such as
ALTER TABLE ... ORDER BY, and rollups of the table size their new tablets against the property value.
tablet_reshard_target_size, including any later change to that configuration. 0, negative values, and non-numeric values are rejected.
If the FE configuration tablet_reshard_target_size is set to 0, automatic split and merge are disabled for all tables, including tables with the table property. The table property takes effect again after the configuration is set back to a positive value.
Note
SHOW CREATE TABLE returns the tablet_reshard_target_size property of a table that has it. Where range distribution is not the default, that is, when the FE configuration enable_range_distribution is false or in shared-nothing mode, the returned statement would create a hash-bucketed or randomly bucketed table, so it fails because the property is supported only on range-distributed tables. A version that does not support the property rejects it as an unknown property. Remove the property before you run the statement in these environments.
Examples
Create new tables with Range-based Distribution semantic
The following examples omit the partition syntax. Duplicate key tables:colocate_with property in the format <colocation_group>:<colocated_column>[,<colocated_column>]:
- The colocated columns must be a prefix of the sort columns.
- Tables in the same colocation group must have the same type, number, and order of colocated columns.
- The type of a colocated column cannot be changed after the table is created, including increasing the length of a VARCHAR column.
- You can change the sort key online after the table is created (
ALTER TABLE ... ORDER BY, adding or dropping a key column, or widening an integer sort-key column), as long as the new sort key still starts with the colocated columns, in the same order and with the same types. A change that drops, reorders, or changes the type of a colocated column is rejected. The table stays in its colocation group and keeps using Colocate Join. - Default colocated columns are the sort columns.
- If
colocate_withspecifies only the colocation group and a sort key change makes the sort key longer than the colocated columns, the database rewrites the property to the explicit form<colocation_group>:<colocated_column>[,<colocated_column>], whichSHOW CREATE TABLEreturns from then on. - Rollups and synchronous materialized views are supported, as long as the sort key of the rollup or view starts with the colocated columns, in the same order and with the same types. A rollup defined in
CREATE TABLE ... ROLLUP (...)is sorted by its key columns, and anORDER BYwritten in it is not used, so its key columns must start with the colocated columns. The sort key of a synchronous materialized view is its leading non-aggregated columns, inSELECTorder. For a view withoutGROUP BY, aggregation, orDISTINCT, the sort key is a prefix of theSELECTlist (at most three columns and 36 bytes; it ends with the first VARCHAR column, or before the first column whose type cannot be a key, such as FLOAT or DOUBLE), andORDER BYdoes not change it. To choose the sort key of such a projection, useALTER TABLE ... ADD ROLLUP ... ORDER BY (...)instead. The sort key changes described above are not supported on a table that has a rollup or synchronous materialized view.
Optimize existing tables by splitting or merging tablets
For detailed instructions on splitting and merging tablets, see ALTER TABLE - Modify the tablet size.- Split all tablets that meet the conditions in the table to the table’s target size (10 GB by default).
- Merge all tablets that meet the conditions in the table to a target size of 2 GB.
Limitations
The following operations are not supported on tables with Range-based Distribution:
For rollup-like aggregation use cases, use an asynchronous materialized view with an explicit
REFRESH clause or a DISTRIBUTED BY clause, for example:
Set the number of buckets
Buckets reflect how data files are actually organized in the database.At table creation
- Automatically set the number of buckets (recommended) Since v2.5.7, the database supports automatically setting the number of buckets based on machine resources and data volume for a partition. Tip If the raw data size of a partition exceeds 100 GB, we recommend that you manually configure the number of buckets using Method 2.
- To enable the on-demand and dynamic increase of the number of buckets, you need to set the table property
PROPERTIES("bucket_size"="xxx")to specify the size of a single bucket. If the data volume in a partition is small, you can set thebucket_sizeto 1 GB. Otherwise, you can set thebucket_sizeto 4 GB. - Once the on-demand and dynamic increase of the number of buckets is enabled, and you need to rollback to version 3.1, you have to first delete the table which enables the dynamic increase in the number of buckets. Then you need to manually execute a metadata checkpoint using ALTER SYSTEM CREATE IMAGE before rolling back.
-
Manually set the number of buckets
Since v2.4.0, the database supports using multiple threads to scan a tablet in parallel during a query, thereby reducing the dependency of scanning performance on the tablet count. We recommend that each tablet contain about 10 GB of raw data. For shared-data clusters of v4.1 or later, which support large-capacity tablets, we recommend that each tablet contain 10 GB to 50 GB of data, and no more than 100 GB. If you intend to manually set the number of buckets, you can estimate the amount of data in each partition of a table and then decide the number of tablets.
To enable parallel scanning on tablets, make sure the
enable_tablet_internal_parallelparameter is set toTRUEglobally for the entire system (SET GLOBAL enable_tablet_internal_parallel = true;).
After table creation
- Automatically set the number of buckets (recommended) Since v2.5.7, the database supports automatically setting the number of buckets based on machine resources and data volume for a partition. Tip If the raw data size of a partition exceeds 100 GB, we recommend that you manually configure the number of buckets using Method 2.
- To enable the on-demand and dynamic increase of the number of buckets, you need to set the table property
PROPERTIES("bucket_size"="xxx")to specify the size of a single bucket. If the data volume in a partition is small, you can set thebucket_sizeto 1 GB. Otherwise, you can set thebucket_sizeto 4 GB. - Once the on-demand and dynamic increase of the number of buckets is enabled, and you need to rollback to version 3.1, you have to first delete the table which enables the dynamic increase in the number of buckets. Then you need to manually execute a metadata checkpoint using ALTER SYSTEM CREATE IMAGE before rolling back.
- Manually set the number of buckets You can also manually specify the buckets number. To calculate the number of buckets for a partition, you can refer to the approach used when manually setting the number of buckets at table creation, as mentioned above.
View the number of buckets
After creating a table, you can execute SHOW PARTITIONS to view the number of buckets set by the database for each partition. Tables configured with hash bucketing have a fixed number of buckets per partition. Info- As for a table configured with random bucketing which enable the on-demand and dynamic increase of the number of buckets, the number of buckets in each partition dynamically increases. So the returned result displays the current number of buckets for each partition.
- For this table type, the actual hierarchy within a partition is as follows: partition > subpartition > bucket. To increase the number of buckets, the database actually adds a new subpartition which includes a certain number of buckets. As a result, the SHOW PARTITIONS statement may return multiple data rows with the same partition name, which show the information of the subpartitions within the same partition.
Optimize data distribution after table creation (since 3.2)
NOTICE The database’s shared-data mode currently does not support this feature.As query patterns and data volume evolve in business scenarios, the configurations specified at table creation, such as the bucketing method, the number of buckets, and the sort key, may no longer be suitable for the new business scenario and even may cause query performance to decrease. At this point, you can use
ALTER TABLE to modify the bucketing method, the number of buckets, and the sort key to optimize data distribution. For example:
- Increase the number of buckets when data volume within partitions is significantly increased When the data volume within partitions becomes significantly larger than before, it is necessary to modify the number of buckets to maintain tablet sizes generally within the range of 1 GB to 10 GB.
-
Modify the bucketing key to avoid data skew
When the current bucketing key can cause data skew (for example, only the
k1column is configured as the bucketing key), it is necessary to specify more suitable columns or add additional columns to the bucketing key. For example: -
Adapting the sort key due to changes in query patterns
If the business query patterns are significantly changed and additional columns are used as conditional columns, it can be beneficial to adjust the sort key. For example: