十七、逻辑结构:索引管理
环境准备
su - omm
gsql -r
索引是一个指向表中数据的指针。一个数据库中的索引与一本书的索引目录是非常相似的。
索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。
1.创建表,在表中创建索引
删除表
drop table if exists test2;
创建新表
create table test2(id serial primary key,testnum serial);
创建索引
create index idx_test_testnum on test2(testnum);
--查看索引
\di
语法为:index+索引名+on+表名(字段名)表示以某一字段为索引。

2.通过hint使用索引
–测试准备,创建表customer,并插入数据
CREATE TABLE customer
(
ca_address_sk integer NOT NULL ,
ca_address_id character(16),
ca_street_number character(10) ,
ca_street_name character varying(60) ,
ca_street_type character(15) ,
ca_suite_number character(10) ,
ca_city character varying(60) ,
ca_county character varying(30) ,
ca_state character(2) ,
ca_zip character(10) ,
ca_country character varying(20) ,
ca_gmt_offset numeric(5,2) ,
ca_location_type character(20)
);
insert into customer values
(1, 'AAAAAAAABAAAAAAA', '18', 'Jackson', 'Parkway', 'Suite 280', 'Fairfield', 'Maricopa County', 'AZ', '86192' ,'United States', -7.00, 'condo'),
(2, 'AAAAAAAACAAAAAAA', '362', 'Washington 6th', 'RD', 'Suite 80', 'Fairview', 'Taos County', 'NM', '85709', 'United States', -7.00, 'condo'),
(3, 'AAAAAAAADAAAAAAA', '585', 'Dogwood Washington', 'Circle', 'Suite Q', 'Pleasant Valley', 'York County', 'PA', '12477', 'United States', -5.00, 'single family');
--创建索引
create index customer_idx on customer(ca_address_sk);

--通过hint强制使用索引,查看执行计划
EXPLAIN SELECT /*+ indexscan(customer customer_idx ) */
* FROM customer WHERE ca_address_sk<100;

强制优化器使用上刚才设立的索引,提高了效率。
3.rename索引
ALTER INDEX idx_test_testnum RENAME TO idx_test_testnum_new;

重新命名完以后再用 \di语句查看索引名,如图所示,已经被修改了。
4.重建索引
--重建一个单独索引
ALTER INDEX idx_test_testnum_new REBUILD;
REINDEX INDEX idx_test_testnum_new;
--重建所有索引
reindex table test;

重建一个单独索引,需要使用alter语句+REBUILD,然后再使用REINDEX语句 重建索引
重建所有索引,则只需要reindex下就行。
5.移动索引到其他表空间
-创建表空间myindex_ts:
CREATE TABLESPACE myindex_ts RELATIVE LOCATION 'tablespace/myindex_ts1';
--将索引idx_test_testnum_new移动到表空间myindex_ts:
ALTER INDEX idx_test_testnum_new SET TABLESPACE myindex_ts;
--查看索引所在的表空间
select * from pg_indexes where tablename = 'test2';
--或
select * from pg_indexes where indexname = 'idx_test_testnum_new';

先创建一个表空间,然后使用alter语句移动索引,
最后用select 语句查询 pg_indexs
6.删除索引
drop index idx_test_testnum_new;

删除的语句较为简单,drop+index+索引名即可
总结:本节课有关openGauss的逻辑结构新部分—————索引,索引的存在大大加快了数据库搜索的速度。但不恰当的索引只会降低性能。索引的相关语法包括了创建索引,使用hint强制使用索引,重命名索引,重建索引,移动索引到新的表空间,删除索引等等。这些语法也比较常见和常用,需要加强记忆。
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




