解析OceanBase v4.2函数索引进行查询优化

embedded/2024/9/22 17:56:53/

一、如何通过函数索引来进行查询优化

函数索引是一种优化查询的技术,其主要作用在于提升包含函数调用的查询语句的执行速度。当查询语句中包含函数调用时,数据库系统需要逐行执行函数计算,这无疑会增加查询的复杂性,导致查询速度下降。然而,通过创建函数索引,我们可以在查询时直接定位到匹配的函数值,从而避免重复计算,提高查询的速度。下面,我们将通过一个具体示例来展示如何利用函数索引来优化查询性能。

假设有一张表t1,t1中有一个数据类型为date的列date_col:

create table t1(date_col date, sales_col int, name_col varchar(10));

如果需要获取3月份的数据,那么可以使用Month()函数来查询:

select * from t1 where month(date_col) = 3;

这种场景下,数据库需要为表中每行计算month(date_col),过滤掉不符合"month(date_col) = 3"的行。如果需要频繁使用月份信息来过滤数据,每次都需要重新计算month(date_col),就会造成大量开销。因此可以在date_col上建一个函数索引,将month(date_col)存储到了索引表中,来加速查询,创建函数索引的语句如下:

create index i1 on t1((month(date_col)));

建立索引后,查询时就可以直接使用该索引,避免了对每个行进行函数计算,提高了查询效率。

explain select * from t1 where month(date_col) = 3;
+-------------------------------------------------------------------------------------------------+
| Query Plan                                                                                      |
+-------------------------------------------------------------------------------------------------+
| ==================================================                                              |
| |ID|OPERATOR        |NAME  |EST.ROWS|EST.TIME(us)|                                              |
| --------------------------------------------------                                              |
| |0 |TABLE RANGE SCAN|t1(i1)|1       |7           |                                              |
| ==================================================                                              |
| Outputs & filters:                                                                              |
| -------------------------------------                                                           |
|   0 - output([t1.date_col], [t1.sales_col], [t1.name_col]), filter(nil), rowset=16              |
|       access([t1.__pk_increment], [t1.date_col], [t1.sales_col], [t1.name_col]), partitions(p0) |
|       is_index_back=true, is_global_index=false,                                                |
|       range_key([t1.SYS_NC19$], [t1.__pk_increment]), range(3,MIN ; 3,MAX),                     |
|       range_cond([t1.SYS_NC19$ = 3])                                                            |
+-------------------------------------------------------------------------------------------------+

二、OceanBase 4.2在MySQL模式下支持函数索引功能

OceanBase 4.1 以及之前的版本中,已在Oracle模式下支持了函数索引功能。OceanBase 4.2 在MySQL模式支持函数索引功能,兼容MySQL 8.0。

示例1:使用create index语句创建函数索引。

语法如下:

CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_nameON tbl_name (expr,...)[index_option] ...key_part: (expr) [ASC | DESC]

expr是一个合法的函数索引表达式,且允许是布尔表达式,例如"c1=c1"。与MySQL不同的是,OceanBase禁止在函数索引的定义中引用生成列。

例如以下语句在t1_func表上创建了一个索引定义是c1+c2 < 1的函数索引i1。

create table t1_func(c1 int, c2 int);
create index i1 on t1_func ((c1+c2 < 1));

示例2:使用alter table语句创建函数索引。

语法如下:

ALTER TABLE tbl_name[alter_option [, alter_option] ...][partition_options]alter_option: {table_options| ADD {INDEX | KEY} [index_name][index_type] (key_part,...) [index_option] ...| ADD SPATIAL [INDEX | KEY] [index_name](key_part,...) [index_option] ...| ...key_part: (expr) [ASC | DESC]

例如以下语句在t1_func上添加了3个函数索引,其中一个名字是i2,另外两个由系统自动生成的名称,格式为‘functional_index’前缀加编号。

alter table t1_func add index ((concat(c1,'a')));
alter table t1_func add index ((c1+1));
alter table t1_func add index i2 ((concat(c1,'a')));

示例3:使用create table语句在建表时创建函数索引。

语法如下:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name(create_definition,...)[table_options][partition_options]create_definition: {col_name column_definition| {INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option] ...| SPATIAL [INDEX | KEY] [index_name] (key_part,...)[index_option] ...| [CONSTRAINT [symbol]] UNIQUE [INDEX | KEY][index_name] [index_type] (key_part,...)[index_option] ......
}key_part: (expr) [ASC | DESC]

例如以下语句在创建表t2_func时,创建了一个函数索引i1。

create table t2_func (c1 int, c2 int, index i1 ((c1+1)), unique key ((c1+c2)));

可以使用show create table语句查看创建的函数索引:

show create table t1_func;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t1_func | CREATE TABLE `t1_func` (`c1` int(11) DEFAULT NULL,`c2` int(11) DEFAULT NULL,KEY `i1` (((`c1` + `c2`) < 1)) BLOCK_SIZE 16384 LOCAL,KEY `functional_index` (concat(`c1`,'a')) BLOCK_SIZE 16384 LOCAL,KEY `functional_index_2` ((`c1` + 1)) BLOCK_SIZE 16384 LOCAL,KEY `i2` (concat(`c1`,'a')) BLOCK_SIZE 16384 LOCAL
) DEFAULT CHARSET = utf8mb4 ROW_FORMAT = DYNAMIC COMPRESSION = 'lz4_1.0' REPLICA_NUM = 1 BLOCK_SIZE = 16384 USE_BLOOM_FILTER = FALSE TABLET_SIZE = 134217728 PCTFREE = 0 |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+show create table t2_func;
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                                                                                                                                                                                       |
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t2_func | CREATE TABLE `t2_func` (`c1` int(11) DEFAULT NULL,`c2` int(11) DEFAULT NULL,UNIQUE KEY `functional_index` ((`c1` + `c2`)) BLOCK_SIZE 16384 LOCAL,KEY `i1` ((`c1` + 1)) BLOCK_SIZE 16384 LOCAL
) DEFAULT CHARSET = utf8mb4 ROW_FORMAT = DYNAMIC COMPRESSION = 'lz4_1.0' REPLICA_NUM = 1 BLOCK_SIZE = 16384 USE_BLOOM_FILTER = FALSE TABLET_SIZE = 134217728 PCTFREE = 0 |
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

也可以使用show index命令来查看已创建的函数索引,例如:

show index from t1_func;
+---------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+---------------------+
| Table   | Non_unique | Key_name           | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment   | Index_comment | Visible | Expression          |
+---------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+---------------------+
| t1_func |          1 | i1                 |            1 | SYS_NC18$   | A         |        NULL | NULL     | NULL   | YES  | BTREE      | available |               | YES     | ((`c1` + `c2`) < 1) |
| t1_func |          1 | functional_index   |            1 | SYS_NC19$   | A         |        NULL | NULL     | NULL   | YES  | BTREE      | available |               | YES     | concat(`c1`,'a')    |
| t1_func |          1 | functional_index_2 |            1 | SYS_NC20$   | A         |        NULL | NULL     | NULL   | YES  | BTREE      | available |               | YES     | (`c1` + 1)          |
| t1_func |          1 | i2                 |            1 | SYS_NC19$   | A         |        NULL | NULL     | NULL   | YES  | BTREE      | available |               | YES     | concat(`c1`,'a')    |
+---------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+---------------------+show index from t2_func;
+---------+------------+------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+---------------+
| Table   | Non_unique | Key_name         | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment   | Index_comment | Visible | Expression    |
+---------+------------+------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+---------------+
| t2_func |          1 | i1               |            1 | SYS_NC18$   | A         |        NULL | NULL     | NULL   | YES  | BTREE      | available |               | YES     | (`c1` + 1)    |
| t2_func |          0 | functional_index |            1 | SYS_NC19$   | A         |        NULL | NULL     | NULL   | YES  | BTREE      | available |               | YES     | (`c1` + `c2`) |
+---------+------------+------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+---------------+

三、OceanBase 4.2禁止非确定性函数用于函数索引

OceanBase 4.2版本禁止了一些非确定性的系统函数被用于创建函数索引和生成列,以提升稳定性。这些系统函数的结果会随着系统或用户环境的变化而变化的函数,例如:

select current_time();
+----------------+
| current_time() |
+----------------+
| 20:44:22       |
+----------------+select current_time();
+----------------+
| current_time() |
+----------------+
| 20:44:24       |
+----------------+

SQL模式">MySQL模式

以下函数被禁止用于生成列和函数索引:

aes_decryptfrom_unixtimestatement_digest
aes_encrypthost_ipsys_privilege_check
benchmarkicu_versionsysdate
connection_idis_serving_tenanttime_to_usec
current_datelast_excution_idunix_timestamp
current_timelast_insert_idusec_to_time
current_timestamplnnvluser
current_userlocaltimestamputc_date
current_user_privmysql_portutc_time
databasename_constutc_timestamp
des_decryptob_versionuuid
des_encryptranduuid_short
des_hex_strrandom_bytesvalidate_password_strength
dumprow_countversion
encryptrpc_portweight_string
found_rowssleep

一些时间相关的系统函数禁止在参数为TIME类型时用于函数索引,例如:

create table time_func(c1 time, c2 date);
create index i1 on time_func((date(c1)));
ERROR 3758 (HY000): Expression of functional index contains a disallowed function.

涉及以下函数:

adddatedayofyeartimestampdiff
datelast_dayto_days
date_submonthweek
datediffmonthnameweekday
dayquarterweekofyear
daynametimestampyear
dayofmonthtimestamp_nvlyearweek
dayofweektimestampadd

此外,cast函数将time类型的参数转换成非time的其他时间类型,或者将timestamp类型的参数转换为非timestamp的其他数据类型时,也被禁止用于生成列和函数索引,例如:

create index i1 on time_func((cast(c1 as DATE)));
ERROR 3758 (HY000): Expression of functional index contains a disallowed function.

Oracle模式

与之前的版本相比,4.2版本在Oracle模式下新增禁止了以下函数用于生成列和函数索引:

dumpob_versionrpc_port
host_ipregexp_countscn_to_timestamp
is_serving_tenantregexp_instrtimestamp_to_scn
last_trace_idregexp_substr

以下系统函数在参数是字符串类型时禁止用于函数索引:

add_monthsnext_day
last_daytimestamp_nvl
months_between

例如:

create table t1(c1 date, c2 varchar(40), c3 timestamp);
create index i1 on t1(ADD_MONTHS(c2, 1));
ORA-01743: only pure functions can be indexed

此外,cast函数在将字符串转为时间类型、将时间类型转为字符串、将不带timezone信息的时间类型转为带timezone信息的时间类型的情况下禁止用于函数索引,例如:

create table t2(c1 varchar(20), c2 date, c3 TIMESTAMP WITH TIME ZONE, c4 number);
create index i1 on t2(cast(c1 as DATE));
ORA-01743: only pure functions can be indexedcreate index i1 on t2(cast(c2 as TIMESTAMP WITH TIME ZONE));
ORA-01743: only pure functions can be indexedcreate index i1 on t2(cast(c3 as VARCHAR(10)));
ORA-01743: only pure functions can be indexed

四、总结

Oceanbase 4.2版本支持了在MySQL模式下创建和使用函数索引,并且禁止了部分非确定性函数用于创建函数索引和生成列以提升稳定性。但是其中部分函数在MySQL和Oracle中是允许用于函数索引的,例如:

(Mysql 8.0.31)
mysql> create table time_func(c1 timestamp, c2 date);
Query OK, 0 rows affected (0.04 sec)mysql> create index i1 on time_func((date(c1)));
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

Oceanbase后续版本将会放开对这些函数的限制,进一步提升兼容性。


http://www.ppmy.cn/embedded/9869.html

相关文章

力扣HOT100 - 25. K 个一组翻转链表

解题思路&#xff1a; class Solution {public ListNode reverseKGroup(ListNode head, int k) {ListNode dum new ListNode(0, head);ListNode pre dum;ListNode end dum;while (end.next ! null) {for (int i 0; i < k && end ! null; i) {end end.next;}if …

c++中一些常用库函数

1.最大公约数 需要包括头文件#include<algorithm>,直接写__gcd(a,b),就是求a与b的最大公约数。 #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #include<queue> #include<stack> #include<map>…

C语言案例——输出以下图案(两个对称的星型三角形)

目录 图片代码 图片 代码 #include<stdio.h> int main() {int i,j,k;//先输出上半部图案for(i0;i<3;i){for(j0;j<2-i;j)printf(" ");for(k0;k<2*i;k)printf("*");printf("\n");}//再输出下半部分图案for(i0;i<2;i){for(j0;j&…

springboot使用Mybatis中兼容多数据源的databaseId(databaseIdProvider)的简单使用方法

最近有兼容多数据库的需求&#xff0c;原有数据库使用的mysql&#xff0c;现在需要同时兼容mysql和pgsql&#xff0c;后期可能会兼容更多。 mysql和pgsql很多语法和函数不同&#xff0c;所以有些sql需要写两份&#xff0c;于是在全网搜索如何在mapper中sql不通用的情况下兼容多…

配置全局代理上网

#准备一台机器(160)&#xff0c;DNS注释掉 直接访问不行 curl https://www.baidu.com #代理访问OK curl -x 192.141.46.161:8888 https://www.baidu.com #CentOS设置全局代理 vi ~/.bashrc #加入以下内容 export http_proxyhttp://192.141.46.161:8888 export https_proxy…

为什么js无法通过contentDocument获取到iframe内容

最近在开发一个附件预览的页面&#xff0c;考虑到附件的安全性由后端对内容进行了加密&#xff0c;前端负责在页面引入iframe标签来加载数据&#xff0c;在这个过程中需要实时获取到iframe标签的渲染状态来判断什么时候loading结束&#xff1a; 这里我通过标签的方式来获取到i…

nacos配置mysql(windows)

nacos默认是使用的内置数据库derby ,可通过配置修改成mysql,修改成mysql之后&#xff0c;之前配置在derby的数据会丢失 本文使用mysql版本为8.0.22 nacos版本为2.3.1 在mysql里面先创建一个数据库test(名称自定义&#xff0c;和后面配置文件里面的一样就好了) 在上面创建的数据…

实验7-4:补全代码,插入操作

实验7-4&#xff1a;补全代码&#xff0c;插入操作 【问题描述】 初始化一维数组中的9个元素a[10]{2,5,6,8,11,15,17,20,25}&#xff0c;要求该数组已经按升序排列&#xff0c;从键盘输入一个整数num&#xff0c;并将其插入到数组a中&#xff0c;要求插入操作完成后&#xff0…