暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

MemFireDB SQL语法 - CREATE INDEX 语句(创建索引)

原创 小小亮 2021-06-10
530

CREATE INDEX

概要

使用CREATE INDEX语句在指定表的指定列上创建索引。索引主要用于提高查询性能。

语法

create_index ::= CREATE [ UNIQUE ] INDEX [ [ IF NOT  EXISTS ] name ]                   ON [ ONLY ] table_name ( index_elem [ , ... ] )                   [ INCLUDE ( column_name [ , ... ] ) ]                   [ WHERE predicate ]index_elem ::= { column_name | ( expression ) }                  [  operator_class_name ] [ HASH | ASC | DESC ]                  [  NULLS { FIRST | LAST } ] 

语义

UNIQUE 强制要求不允许表中出现重复值

INCLUDE指定将作为非关键列包含在索引中的列集合。

WHERE部分索引是建立在只包括满足所where规定的条件的行组成的表的子集的索引。它可用于从索引中排除NULL或公共值,或仅包含感兴趣的行。这将加快对表的写入速度,因为不需要索引包含公共列值的行。它还将减小索引的大小,从而提高使用该索引的读取查询的速度。

name 指定要创建的索引的名称。

table_name 指定要建立索引的表的名称。

column_name 指定表的列名。

expression 指定表的一列或多列,并且必须用括号括起来。

  • HASH-使用列的哈希值。这是第一列的默认选项,用于对索引表进行哈希分区。
  • ASC—升序排列。这是索引的第二列和后续列的默认选项。
  • DESC —降序排列。
  • NULLS FIRST-指定null排在非null之前。当指定DESC时,这是默认设置。
  • NULLS LAST-指定null排在非null之后。如果未指定DESC,则为默认设置。

SPLIT INTO 对于散列索引,可以使用该SPLIT INTO子句指定要为索引创建的tablet的数量。使用 SPLIT INTO 预先分割索引可索引将工作负载分配到生产集群上。例如,如果您有3台服务器,则将索引分为30个tablet可以提供更高的索引写吞吐量。

例子

创建具有哈利排序列的唯一索引。

CREATE TABLE products(id int PRIMARY KEY,                               name text,                               code text);CREATE UNIQUE INDEX ON products(code);\d products             Table "public.products"Column | Type   | Collation | Nullable | Default--------+---------+-----------+----------+---------id   | integer |      | not null |name  | text    |      |     |code  | text    |      |     |Indexes:    "products_pkey" PRIMARY KEY, lsm (id HASH)    "products_code_idx" UNIQUE, lsm (code HASH)  

用升序键创建索引。

CREATE INDEX products_name ON products(name ASC);\d products_name    Index "public.products_name"Column | Type |  Key? | Definition--------+------+------+------------name  | text | yes | namelsm, for table "public.products

创建具有升序排序键的索引,并包括其他列作为非键列。

CREATE INDEX products_name_code ON products(name)  INCLUDE (code);\d products_name_code; Index  "public.products_name_code" Column | Type |  Key? | Definition--------+------+------+------------name  | text | yes | namecode  | text | no  | codelsm, for table "public.products"

指定索引的tablet数量。

CREATE TABLE employees (id int PRIMARY KEY, first_name  TEXT, last_name TEXT) SPLIT INTO 10 TABLETS;CREATE INDEX ON employees(first_name, last_name) SPLIT  INTO 10 TABLETS;

一个维护货运信息的应用程序。它有一个shipments表,该表的列为delivery_status。如果应用程序需要频繁访问 shipments表 ,则可以使用部分索引排除货件状态为 delivered 的行。

create table shipments(id int, delivery_status text,  address text, delivery_date date);create index shipment_delivery on  shipments(delivery_status, address, delivery_date) where delivery_status !=  'delivered'; 
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论