华为云用户手册

  • 对于case和coalesce,在TD兼容模式下的处理 如果所有输入都是相同的类型,并且不是unknown类型,那么解析成这种类型。 如果所有输入都是unknown类型则解析成text类型。 如果输入字符串(包括unknown,unknown当text来处理)和数字类型,那么解析成字符串类型,如果是其他不同的类型范畴,则报错。 如果输入类型是同一个类型范畴,则选择该类型的优先级较高的类型。 把所有输入转换为所选的类型。如果从给定的输入到所选的类型没有隐式转换则失败。
  • 创建索引 为了加速文本搜索,可以创建GIN索引。 1 openGauss=# CREATE INDEX pgweb_idx_1 ON tsearch.pgweb USING gin(to_tsvector('english', body)); to_tsvector()函数有两个版本。只输一个参数的版本和输两个参数的版本。只输一个参数时,系统默认采用default_text_search_config所指定的分词器。 请注意:创建索引时必须使用to_tsvector的两参数版本。只有指定了分词器名称的全文检索函数才可以在索引表达式中使用。这是因为索引的内容必须不受default_text_search_config的影响,否则索引内容可能不一致。由于default_text_search_config的值可以随时调整,从而导致不同条目生成的tsvector采用了不同的分词器,并且没有办法区分究竟使用了哪个分词器。正确地转储和恢复这样的索引也是不可能的。 因为在上述创建索引中to_tsvector使用了两个参数,只有当查询时也使用了两个参数,且参数值与索引中相同时,才会使用该索引。也就是说,WHERE to_tsvector('english', body) @@ 'a & b' 可以使用索引,但WHERE to_tsvector(body) @@ 'a & b'不能使用索引。这确保只使用这样的索引——索引各条目是使用相同的分词器创建的。 索引中的分词器名称由另一列指定时可以建立更复杂的表达式索引。例如: 1 openGauss=# CREATE INDEX pgweb_idx_2 ON tsearch.pgweb USING gin(to_tsvector('ngram', body)); 其中body是pgweb表中的一列。当对索引的各条目使用了哪个分词器进行记录时,允许在同一索引中存在混合分词器。在某些场景下这将是有用的。例如,文档集合中包含不同语言的文档时。再次强调,打算使用索引的查询必须措辞匹配,例如,WHERE to_tsvector(config_name, body) @@ 'a & b'与索引中的to_tsvector措辞匹配。 索引甚至可以连接列: 1 openGauss=# CREATE INDEX pgweb_idx_3 ON tsearch.pgweb USING gin(to_tsvector('english', title || ' ' || body)); 另一个方法是创建一个单独的tsvector列控制to_tsvector的输出。下面的例子是title和body的连接, 当其它是NULL的时候,使用coalesce确保一个字段仍然会被索引: 12 openGauss=# ALTER TABLE tsearch.pgweb ADD COLUMN textsearchable_index_col tsvector;openGauss=# UPDATE tsearch.pgweb SET textsearchable_index_col = to_tsvector('english', coalesce(title,'') || ' ' || coalesce(body,'')); 然后为加速搜索创建一个GIN索引: 1 openGauss=# CREATE INDEX textsearch_idx_4 ON tsearch.pgweb USING gin(textsearchable_index_col); 现在,就可以执行一个快速全文搜索了: 1 2 3 4 5 6 7 8 91011 openGauss=# SELECT title FROM tsearch.pgweb WHERE textsearchable_index_col @@ to_tsquery('north & america') ORDER BY last_mod_date DESC LIMIT 10; title -------- Canada Mexico(2 rows) 相比于一个表达式索引,单独列方法的一个优势是:它没有必要在查询时明确指定分词器以便能使用索引。正如上面例子所示,查询可以依赖于default_text_search_config。另一个优势是搜索比较快速,因为它没有必要重新利用to_tsvector调用来验证索引匹配。表达式索引方法更容易建立,且它需要较少的磁盘空间,因为tsvector形式没有明确存储。 父主题: 表和索引
  • 解析文档 GaussDB中提供了to_tsvector函数把文档处理成tsvector数据类型。 1 to_tsvector([ config regconfig, ] document text) returns tsvector to_tsvector将文本文档解析为token,再将token简化到词素,并返回一个tsvector。其中tsvector中列出了词素及它们在文档中的位置。文档是根据指定的或默认的文本搜索分词器进行处理的。这里有一个简单的例子: 1234 openGauss=# SELECT to_tsvector('english', 'a fat cat sat on a mat - it ate a fat rats'); to_tsvector----------------------------------------------------- 'ate':9 'cat':3 'fat':2,11 'mat':7 'rat':12 'sat':4 通过以上例子可发现结果tsvector不包含词a、on或者it,rats变成rat,并且忽略标点符号-。 to_tsvector函数内部调用一个解析器,将文档的文本分解成token并给每个token指定一个类型。对于每个token,有一系列词典可供查询。词典系列因token类型的不同而不同。识别token的第一本词典将发出一个或多个标准词素来表示token。例如: rats变成rat因为词典认为词rats是rat的复数形式。 有些词被作为停用词(请参考停用词),这样它们就会被忽略,因为它们出现得太过频繁以致于搜索中没有用处。比如例子中的a、on和it。 如果没有词典识别token,那么它也被忽略。在这个例子中,符号“-”被忽略,因为词典没有给它分配token类型(空间符号),即空间记号永远不会被索引。 语法解析器、词典和要索引的token类型由选定的文本搜索分词器决定。可以在同一个数据库中有多种不同的分词器,以及提供各种语言的预定义分词器。在以上例子中,使用缺省分词器english。 函数setweight可以给tsvector的记录加权重,权重是字母A、B、C、D之一。这通常用于标记来自文档不同部分的记录,比如标题、正文。之后,这些信息可以用于排序搜索结果。 因为to_tsvector(NULL)会返回空,当字段可能是空的时候,建议使用coalesce。以下是推荐的为结构化文档创建tsvector的方法: 1 2 3 4 5 6 7 8 910 openGauss=# CREATE TABLE tsearch.tt (id int, title text, keyword text, abstract text, body text, ti tsvector);openGauss=# INSERT INTO tsearch.tt(id, title, keyword, abstract, body) VALUES (1, 'China', 'Beijing', 'China','China, officially the People''s Republic of China (PRC), located in Asia, is the world''s most populous state.');openGauss=# UPDATE tsearch.tt SET ti = setweight(to_tsvector(coalesce(title,'')), 'A') || setweight(to_tsvector(coalesce(keyword,'')), 'B') || setweight(to_tsvector(coalesce(abstract,'')), 'C') || setweight(to_tsvector(coalesce(body,'')), 'D');openGauss=# DROP TABLE tsearch.tt; 上例使用setweight标记已完成的tsvector中的每个词的来源,并且使用tsvector连接操作符||合并标记过的tsvector值,处理tsvector一节详细介绍了这些操作。 父主题: 控制文本搜索
  • 解析查询 GaussDB提供了函数to_tsquery和plainto_tsquery将查询转换为tsquery数据类型,to_tsquery提供比plainto_tsquery更多的功能,但对其输入要求更严格。 to_tsquery([ config regconfig, ] querytext text) returns tsquery to_tsquery从querytext中创建一个tsquery,querytext必须由布尔运算符& (AND),| (OR)和! (NOT)分割的单个token组成。这些运算符可以用圆括弧分组。换句话说,to_tsquery输入必须遵循tsquery输入的通用规则,具体请参见文本搜索类型。不同的是基本tsquery以token表面值作为输入,而to_tsquery使用指定或默认分词器将每个token标准化成词素,并依据分词器丢弃属于停用词的token。例如: 12345 openGauss=# SELECT to_tsquery('english', 'The & Fat & Rats'); to_tsquery --------------- 'fat' & 'rat'(1 row) 像在基本tsquery中的输入一样,weight(s)可以附加到每个词素来限制它只匹配那些有相同weight(s)的tsvector词素。比如: 12345 openGauss=# SELECT to_tsquery('english', 'Fat | Rats:AB'); to_tsquery ------------------ 'fat' | 'rat':AB(1 row) 同时,*也可以附加到词素来指定前缀匹配: 12345 openGauss=# SELECT to_tsquery('supern:*A & star:A*B'); to_tsquery -------------------------- 'supern':*A & 'star':*AB(1 row) 这样的词素将匹配tsquery中指定字符串和权重的项。 plainto_tsquery([ config regconfig, ] querytext text) returns tsquery plainto_tsquery将未格式化的文本querytext变换为tsquery。类似于to_tsvector,文本被解析并且标准化,然后在存在的词之间插入&(AND)布尔算子。 比如: 12345 openGauss=# SELECT plainto_tsquery('english', 'The Fat Rats'); plainto_tsquery ----------------- 'fat' & 'rat'(1 row) 请注意,plainto_tsquery无法识别布尔运算符、权重标签,或在其输入中的前缀匹配标签: 12345 openGauss=# SELECT plainto_tsquery('english', 'The Fat & Rats:C'); plainto_tsquery --------------------- 'fat' & 'rat' & 'c'(1 row) 在这里,所有输入的标点符号作为空格符号丢弃。 父主题: 控制文本搜索
  • 注释信息函数 col_description(table_oid, column_number) 描述:获取一个表字段的注释 返回类型:text 备注:col_description返回一个表中字段的注释,通过表OID和字段号来声明。 obj_description(object_oid, catalog_name) 描述:获取一个数据库对象的注释 返回类型:text 备注:带有两个参数的obj_description返回一个数据库对象的注释,该对象是通过其OID和其所属的系统表名称声明。比如,obj_description(123456,'pg_class')将返回OID为123456的表的注释。只带一个参数的obj_description只要求对象OID。 obj_description不能用于表字段,因为字段没有自己的OID。 obj_description(object_oid) 描述:获取一个数据库对象的注释 返回类型:text shobj_description(object_oid, catalog_name) 描述:获取一个共享数据库对象的注释 返回类型:text 备注:shobj_description和obj_description差不多,不同之处仅在于前者用于共享对象。一些系统表是通用于GaussDB中所有数据库的全局表,因此这些表的注释也是全局存储的。
  • 系统表信息函数 format_type(type_oid, typemod) 描述:获取数据类型的SQL名称 返回类型:text 备注:format_type通过某个数据类型的类型OID以及可能的类型修饰词,返回其SQL名称。如果不知道具体的修饰词,则在类型修饰词的位置传入NULL。类型修饰词一般只对有长度限制的数据类型有意义。format_type所返回的SQL名称中包含数据类型的长度值,其大小是:实际存储长度len - sizeof(int32),单位字节。原因是数据存储时需要32位的空间来存储用户对数据类型的自定义长度信息,即实际存储长度要比用户定义长度多4个字节。在下例中,format_type返回的SQL名称为“character varying(6)”,6表示varchar类型的长度值是6字节,因此该类型的实际存储长度为10字节。 12345 openGauss=# SELECT format_type((SELECT oid FROM pg_type WHERE typname='varchar'), 10); format_type ---------------------- character varying(6)(1 row) getdistributekey(table_name) 描述:获取一个hash表的分布列。单机环境下不支持分布,该函数返回为空。 pg_check_authid(role_oid) 描述:检查是否存在给定oid的角色名 返回类型:bool 示例: openGauss=# select pg_check_authid(1);pg_check_authid-----------------f(1 row) pg_describe_object(catalog_id, object_id, object_sub_id) 描述:获取数据库对象的描述 返回类型:text 备注:pg_describe_object返回由目录OID,对象OID和一个(或许0个)子对象ID指定的数据库对象的描述。这有助于确认存储在pg_depend系统表中对象的身份。 pg_get_constraintdef(constraint_oid) 描述:获取约束的定义 返回类型:text pg_get_constraintdef(constraint_oid, pretty_bool) 描述:获取约束的定义 返回类型:text 备注:pg_get_constraintdef和pg_get_indexdef分别从约束或索引上使用创建命令进行重构。 pg_get_expr(pg_node_tree, relation_oid) 描述:反编译表达式的内部形式,假设其中的任何Vars都引用第二个参数指定的关系。 返回类型:text pg_get_expr(pg_node_tree, relation_oid, pretty_bool) 描述:反编译表达式的内部形式,假设其中的任何Vars都引用第二个参数指定的关系。 返回类型:text 备注:pg_get_expr反编译一个独立表达式的内部形式,比如一个字段的缺省值。在检查系统表的内容的时候很有用。如果表达式可能包含关键字,则指定他们引用相关的OID作为第二个参数;如果没有关键字,零就足够了。 pg_get_functiondef(func_oid) 描述:获取函数的定义 返回类型:text 示例: openGauss=# select * from pg_get_functiondef(598); headerlines | definition -------------+---------------------------------------------------- 4 | CREATE OR REPLACE FUNCTION pg_catalog.abbrev(inet)+ | RETURNS text + | LANGUAGE internal + | IMMUTABLE STRICT NOT FENCED NOT SHIPPABLE + | AS $function$inet_abbrev$function$ + | (1 row) pg_get_function_arguments(func_oid) 描述:获取函数定义的参数列表(带默认值) 返回类型:text 备注:pg_get_function_arguments返回一个函数的参数列表,需要在CREATE FUNCTION中使用这种格式。 pg_get_function_identity_arguments(func_oid) 描述:获取参数列表来确定一个函数 (不带默认值) 返回类型:text 备注:pg_get_function_identity_arguments返回需要的参数列表用来标识函数,这种形式需要在ALTER FUNCTION中使用,并且这种形式省略了默认值。 pg_get_function_result(func_oid) 描述:获取函数的RETURNS子句 返回类型:text 备注:pg_get_function_result为函数返回适当的RETURNS子句。 pg_get_indexdef(index_oid) 描述:获取索引的CREATE INDEX命令 返回类型:text 示例: openGauss=# select * from pg_get_indexdef(16416); pg_get_indexdef ------------------------------------------------------------------------- CREATE INDEX test3_b_idx ON test3 USING btree (b) TABLESPACE pg_default(1 row) pg_get_indexdef(index_oid, dump_schema_only) 描述:获取索引的CREATE INDEX命令,仅用于dump场景。对于包含local索引的间隔分区表,当dump_schema_only为true时,返回的创建索引语句中不包含自动创建的分区的local索引信息;当dump_schema_only为false时,返回的创建索引语句中包含自动创建的分区的local索引信息。对于非间隔分区表或者不包含local索引的间隔分区分区表,dump_schema_only参数取值不影响函数返回结果。 返回类型:text 示例: openGauss=# CREATE TABLE salesopenGauss-# (prod_id NUMBER(6),openGauss(# cust_id NUMBER,openGauss(# time_id DATE,openGauss(# channel_id CHAR(1),openGauss(# promo_id NUMBER(6),openGauss(# quantity_sold NUMBER(3),openGauss(# amount_sold NUMBER(10,2)openGauss(# )PARTITION BY RANGE( time_id) INTERVAL('1 day')openGauss-# openGauss-# (openGauss(# partition p1 VALUES LESS THAN ('2019-02-01 00:00:00'),openGauss(# partition p2 VALUES LESS THAN ('2019-02-02 00:00:00')openGauss(# );CREATE TABLEopenGauss=# create index index_sales on sales(prod_id) local (PARTITION idx_p1 ,PARTITION idx_p2);CREATE INDEXopenGauss=# -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1);INSERT 0 1openGauss=# select oid from pg_class where relname = 'index_sales'; oid------- 24632(1 row)openGauss=# select * from pg_get_indexdef(24632, true); pg_get_indexdef-------------------------------------------------------------------------------------------------------------------------- CREATE INDEX index_sales ON sales USING btree (prod_id) LOCAL(PARTITION idx_p1, PARTITION idx_p2) TABLESPACE pg_default(1 row)openGauss=# select * from pg_get_indexdef(24632, false); pg_get_indexdef-------------------------------------------------------------------------------------------------------------------------------------------------------- CREATE INDEX index_sales ON sales USING btree (prod_id) LOCAL(PARTITION idx_p1, PARTITION idx_p2, PARTITION sys_p1_prod_id_idx) TABLESPACE pg_default(1 row pg_get_indexdef(index_oid, column_no, pretty_bool) 描述:获取索引的CREATE INDEX命令,或者如果column_no不为零,则只获取一个索引字段的定义。 示例: openGauss=# select * from pg_get_indexdef(16416, 0, false); pg_get_indexdef ------------------------------------------------------------------------- CREATE INDEX test3_b_idx ON test3 USING btree (b) TABLESPACE pg_default(1 row)openGauss=# select * from pg_get_indexdef(16416, 1, false); pg_get_indexdef ----------------- b(1 row) 返回类型:text 备注:pg_get_functiondef为函数返回一个完整的CREATE OR REPLACE FUNCTION语句。 pg_get_keywords() 描述:获取SQL关键字和类别列表 返回类型:setof record 备注:pg_get_keywords返回一组关于描述服务器识别SQL关键字的记录。word列包含关键字。catcode列包含一个分类代码:U表示通用的,C表示列名,T表示类型或函数名,或R表示保留。catdesc列包含了一个可能本地化描述分类的字符串。 pg_get_userbyid(role_oid) 描述:获取给定OID的角色名 返回类型:name 备注:pg_get_userbyid通过角色的OID抽取对应的用户名。 pg_check_authid(role_id) 描述:通过role_id检查用户是否存在 返回类型:text 示例: openGauss=# select pg_check_authid(20);pg_check_authid-----------------f(1 row) pg_get_viewdef(view_name) 描述:为视图获取底层的SELECT命令 返回类型:text pg_get_viewdef(view_name, pretty_bool) 描述:为视图获取底层的SELECT命令,如果pretty_bool为true,行字段可以包含80列。 返回类型:text 备注:pg_get_viewdef重构出定义视图的SELECT查询。这些函数大多数都有两种形式,其中带有pretty_bool参数,且参数为true时,是"适合打印"的结果,这种格式更容易读。另一种是缺省的格式,更有可能被将来的不同版本用同样的方法解释。如果是用于转储,那么尽可能避免使用适合打印的格式。给pretty-print参数传递false生成的结果和没有这个参数的变种生成的结果是完全一样。 pg_get_viewdef(view_oid) 描述:为视图获取底层的SELECT命令 返回类型:text pg_get_viewdef(view_oid, pretty_bool) 描述:为视图获取底层的SELECT命令,如果pretty_bool为true,行字段可以包含80列。 返回类型:text pg_get_viewdef(view_oid, wrap_column_int) 描述:为视图获取底层的SELECT命令;行字段被换到指定的列数,打印是隐含的。 返回类型:text pg_get_tabledef(table_oid) 描述:根据table_oid获取表定义 示例: openGauss=# select * from pg_get_tabledef(16384); pg_get_tabledef ------------------------------------------------------- SET search_path = public; + CREATE TABLE t1 ( + c1 bigint DEFAULT nextval('serial'::regclass)+ ) + WITH (orientation=row, compression=no) + TO GROUP group1;(1 row) 返回类型:text pg_get_tabledef(table_name) 描述:根据table_name获取表定义 示例: openGauss=# select * from pg_get_tabledef('t1'); pg_get_tabledef ------------------------------------------------------- SET search_path = public; + CREATE TABLE t1 ( + c1 bigint DEFAULT nextval('serial'::regclass)+ ) + WITH (orientation=row, compression=no) + TO GROUP group1;(1 row) 返回类型:text 备注:pg_get_tabledef重构出表定义的CREATE语句,包含了表定义本身、索引信息、comments信息。对于表对象依赖的group、schema、tablespace、server等信息,需要用户自己去创建,表定义里不会有这些对象的创建语句。 pg_options_to_table(reloptions) 描述:获取存储选项名称/值对的集合 返回类型:setof record 备注:pg_options_to_table当通过pg_class.reloptions或pg_attribute.attoptions时返回存储选项名称/值对(option_name/option_value)的集合。 pg_tablespace_databases(tablespace_oid) 描述:获取在指定的表空间中有对象的数据库OID集合 返回类型:setof oid 备注:pg_tablespace_databases允许检查表空间的状况,返回在该表空间中保存了对象的数据库OID集合。如果这个函数返回数据行,则该表空间就是非空的,因此不能删除。要显示该表空间中的特定对象,用户需要连接pg_tablespace_databases标识的数据库与查询pg_class系统表。 pg_tablespace_location(tablespace_oid) 描述:获取表空间所在的文件系统的路径 返回类型:text pg_typeof(any) 描述:获取任何值的数据类型 返回类型:regtype 备注:pg_typeof返回传递给他的值的数据类型OID。这可能有助于故障排除或动态构造SQL查询。声明此函数返回regtype,这是一个OID别名类型(请参考对象标识符类型);这意味着它是一个为了比较而显示类型名称的OID。 示例: 1 2 3 4 5 6 7 8 91011 openGauss=# SELECT pg_typeof(33); pg_typeof ----------- integer(1 row)openGauss=# SELECT typlen FROM pg_type WHERE oid = pg_typeof(33); typlen -------- 4(1 row) collation for (any) 描述:获取参数的排序 返回类型:text 备注:表达式collation for返回传递给他的值的排序。 示例: 12345 openGauss=# SELECT collation for (description) FROM pg_description LIMIT 1; pg_collation_for ------------------ "default"(1 row) 值可能是引号括起来的并且模式限制的。如果没有为参数表达式排序,则返回一个null值。如果参数不是排序的类型,则抛出一个错误。 pg_extension_update_paths(name) 描述:返回指定扩展的版本更新路径。 返回类型:text(source text), text(path text), text(target text) pg_get_serial_sequence(tablename, colname) 描述:获取对应表名和列名上的序列。 返回类型:text 示例: openGauss=# select * from pg_get_serial_sequence('t1', 'c1'); pg_get_serial_sequence ------------------------ public.serial(1 row) pg_sequence_parameters(sequence_oid) 描述:获取指定sequence的参数,包含起始值,最小值和最大值,递增值等。 返回类型:int16, int16, int16, int16, Boolean 示例: openGauss=# select * from pg_sequence_parameters(16420); start_value | minimum_value | maximum_value | increment | cycle_option -------------+---------------+---------------------+-----------+-------------- 101 | 1 | 9223372036854775807 | 1 | f(1 row)
  • 模式可见性查询函数 每个函数执行检查数据库对象类型的可见性。对于函数和操作符,如果在前面的搜索路径中没有相同的对象名称和参数的数据类型,则此对象是可见的。对于操作符类,则要同时考虑名称和相关索引的访问方法。 所有这些函数都需要使用OID来标识要需要检查的对象。如果用户想通过名称测试对象,则使用OID别名类型(regclass、regtype、regprocedure、regoperator、regconfig或regdictionary)将会很方便。 比如,如果一个表所在的模式在搜索路径中,并且在前面的搜索路径中没有同名的表,则这个表是可见的。它等效于表可以不带明确模式修饰进行引用。比如,要列出所有可见表的名称: 1 openGauss=# SELECT relname FROM pg_class WHERE pg_table_is_visible(oid); pg_collation_is_visible(collation_oid) 描述:该排序是否在搜索路径中可见。 返回类型:Boolean pg_conversion_is_visible(conversion_oid) 描述:该转换是否在搜索路径中可见。 返回类型:Boolean pg_function_is_visible(function_oid) 描述:该函数是否在搜索路径中可见。 返回类型:Boolean pg_opclass_is_visible(opclass_oid) 描述:该操作符类是否在搜索路径中可见。 返回类型:Boolean pg_operator_is_visible(operator_oid) 描述:该操作符是否在搜索路径中可见。 返回类型:Boolean pg_opfamily_is_visible(opclass_oid) 描述:该操作符族是否在搜索路径中可见。 返回类型:Boolean pg_table_is_visible(table_oid) 描述:该表是否在搜索路径中可见。 返回类型:Boolean pg_ts_config_is_visible(config_oid) 描述:该文本检索配置是否在搜索路径中可见。 返回类型:Boolean pg_ts_dict_is_visible(dict_oid) 描述:该文本检索词典是否在搜索路径中可见。 返回类型:Boolean pg_ts_parser_is_visible(parser_oid) 描述:该文本搜索解析是否在搜索路径中可见。 返回类型:Boolean pg_ts_template_is_visible(template_oid) 描述:该文本检索模板是否在搜索路径中可见。 返回类型:Boolean pg_type_is_visible(type_oid) 描述:该类型(或域)是否在搜索路径中可见。 返回类型:Boolean
  • 访问权限查询函数 DDL类权限ALTER、DROP、COMMENT、INDEX、VACUUM属于所有者固有的权限,隐式拥有。 以下访问权限查询函数仅表示用户是否具有某对象上的某种对象权限,即返回记录在系统表acl字段中的对象权限拥有情况。 has_any_column_privilege(user, table, privilege) 描述:指定用户是否有访问表任何列的权限。 表1 参数类型说明 参数名 合法入参类型 user name, oid table text, oid privilege text 返回类型:Boolean has_any_column_privilege(table, privilege) 描述:当前用户是否有访问表任何列的权限,合法参数类型见表1。 返回类型:Boolean 备注:has_any_column_privilege检查用户是否以特定方式访问表的任何列。其参数可能与has_table_privilege类似,除了访问权限类型必须是SELECT、INSERT、UPDATE、COMMENT或REFERENCES的一些组合。 拥有表的表级别权限则隐含的拥有该表每列的列级权限,因此如果与has_table_privilege参数相同,has_any_column_privilege总是返回true。但是如果授予至少一列的列级权限也返回成功。 has_column_privilege(user, table, column, privilege) 描述:指定用户是否有访问列的权限。 表2 参数类型说明 参数名 合法入参类型 user name, oid table text, oid column text, smallint privilege text 返回类型:Boolean has_column_privilege(table, column, privilege) 描述:当前用户是否有访问列的权限,合法参数类型见表2。 返回类型:Boolean 备注:has_column_privilege检查用户是否以特定方式访问一列。其参数类似于has_table_privilege,可以通过列名或属性号添加列。想要的访问权限类型必须是SELECT、INSERT、UPDATE、COMMENT或REFERENCES的一些组合。 拥有表的表级别权限则隐含的拥有该表每列的列级权限。 has_cek_privilege(user, cek, privilege) 描述:指定用户是否有访问列加密密钥CEK的权限。参数说明如下。 表3 参数类型说明 参数名 合法入参类型 描述 取值范围 user name,oid 用户 用户名字或id。 cek text,oid 列加密密钥 列加密密钥名称或id。 privilege text 权限 USAGE:允许使用指定列加密密钥。 DROP:允许删除指定列加密密钥。 返回类型:Boolean has_cmk_privilege(user, cmk, privilege) 描述:指定用户是否有访问客户端加密主密钥CMK的权限。参数说明如下。 表4 参数类型说明 参数名 合法入参类型 描述 取值范围 user name,oid 用户 用户名字或id。 cmk text,oid 客户端加密主密钥 客户端加密主密钥名称或id。 privilege text 权限 USAGE:允许使用指定客户端加密主密钥。 DROP:允许删除指定客户端加密主密钥。 返回类型:Boolean has_database_privilege(user, database, privilege) 描述:指定用户是否有访问数据库的权限。参数说明如下。 表5 参数类型说明 参数名 合法入参类型 user name, oid database text, oid privilege text 返回类型:Boolean has_database_privilege(database, privilege) 描述:当前用户是否有访问数据库的权限,合法参数类型请参见表5。 返回类型:Boolean 备注:has_database_privilege检查用户是否能以在特定方式访问数据库。其参数类似has_table_privilege。访问权限类型必须是CREATE、CONNECT、TEMPORARY、ALTER、DROP、COMMENT或TEMP(等价于TEMPORARY)的一些组合。 has_directory_privilege(user, directory, privilege) 描述:指定用户是否有访问directory的权限。 表6 参数类型说明 参数名 合法入参类型 user name, oid directory text, oid privilege text 返回类型:Boolean has_directory_privilege(directory, privilege) 描述:当前用户是否有访问directory的权限,合法参数类型请参见表6。 返回类型:Boolean has_foreign_data_wrapper_privilege(user, fdw, privilege) 描述:指定用户是否有访问外部数据封装器的权限。 表7 参数类型说明 参数名 合法入参类型 user name, oid fdw text, oid privilege text 返回类型:Boolean has_foreign_data_wrapper_privilege(fdw, privilege) 描述:当前用户是否有访问外部数据封装器的权限。合法参数类型请参见表7。 返回类型:Boolean 备注:has_foreign_data_wrapper_privilege检查用户是否能以特定方式访问外部数据封装器。其参数类似has_table_privilege。访问权限类型必须是USAGE。 has_function_privilege(user, function, privilege) 描述:指定用户是否有访问函数的权限。 表8 参数类型说明 参数名 合法入参类型 user name, oid function text, oid privilege text 返回类型:Boolean has_function_privilege(function, privilege) 描述:当前用户是否有访问函数的权限。合法参数类型请参见表8。 返回类型:Boolean 备注:has_function_privilege检查一个用户是否能以指定方式访问一个函数。其参数类似has_table_privilege。使用文本字符而不是OID声明一个函数时,允许输入的类型和regprocedure数据类型一样(请参考对象标识符类型)。访问权限类型必须是EXECUTE、ALTER、DROP或COMMENT。 has_language_privilege(user, language, privilege) 描述:指定用户是否有访问语言的权限。 表9 参数类型说明 参数名 合法入参类型 user name, oid language text, oid privilege text 返回类型:Boolean has_language_privilege(language, privilege) 描述:当前用户是否有访问语言的权限。合法参数类型请参见表9。 返回类型:Boolean 备注:has_language_privilege检查用户是否能以特定方式访问一个过程语言。其参数类似has_table_privilege。访问权限类型必须是USAGE。 has_nodegroup_privilege(user, nodegroup, privilege) 描述:检查用户是否有数据库节点访问权限。 返回类型:Boolean 表10 参数类型说明 参数名 合法入参类型 user name, oid nodegroup text, oid privilege text has_nodegroup_privilege(nodegroup, privilege) 描述:检查用户是否有数据库节点访问权限。参数与has_table_privilege类似。访问权限类型必须是USAGE、CREATE、COMPUTE、ALTER或DROP。 返回类型:Boolean has_schema_privilege(user, schema, privilege) 描述:指定用户是否有访问模式的权限。 返回类型:Boolean has_schema_privilege(schema, privilege) 描述:当前用户是否有访问模式的权限。 返回类型:Boolean 备注:has_schema_privilege检查用户是否能以特定方式访问一个模式。其参数类似has_table_privilege。访问权限类型必须是CREATE、USAGE、ALTER、DROP或COMMENT的一些组合。 has_server_privilege(user, server, privilege) 描述:指定用户是否有访问外部服务的权限。 返回类型:Boolean has_server_privilege(server, privilege) 描述:当前用户是否有访问外部服务的权限。 返回类型:Boolean 备注:has_server_privilege检查用户是否能以指定方式访问一个外部服务器。其参数类似has_table_privilege。访问权限类型必须是USAGE、ALTER、DROP或COMMENT之一的值。 has_table_privilege(user, table, privilege) 描述:指定用户是否有访问表的权限。 返回类型:Boolean has_table_privilege(table, privilege) 描述:当前用户是否有访问表的权限。 返回类型:Boolean 备注:has_table_privilege检查用户是否以特定方式访问表。用户可以通过名称或OID(pg_authid.oid)来指定,public表明PUBLIC伪角色,或如果缺省该参数,则使用current_user。该表可以通过名称或者OID声明。如果用名称声明,则在必要时可以用模式进行修饰。如果使用文本字符串来声明所希望的权限类型,这个文本字符串必须是SELECT、INSERT、UPDATE、DELETE、TRUNCATE、REFERENCES、TRIGGER、ALTER、DROP、COMMENT、INDEX或VACUUM之一的值。可以给权限类型添加WITH GRANT OPTION,用来测试权限是否拥有授权选项。也可以用逗号分隔列出的多个权限类型,如果拥有任何所列出的权限,则结果便为true。 示例: 1 2 3 4 5 6 7 8 91011 openGauss=# SELECT has_table_privilege('tpcds.web_site', 'select'); has_table_privilege --------------------- t (1 row)openGauss=# SELECT has_table_privilege('omm', 'tpcds.web_site', 'select,INSERT WITH GRANT OPTION '); has_table_privilege --------------------- t (1 row) has_tablespace_privilege(user, tablespace, privilege) 描述:指定用户是否有访问表空间的权限。 返回类型:Boolean has_tablespace_privilege(tablespace, privilege) 描述:当前用户是否有访问表空间的权限。 返回类型:Boolean 备注:has_tablespace_privilege检查用户是否能以特定方式访问一个表空间。其参数类似has_table_privilege。访问权限类型必须是CREATE、ALTER、DROP或COMMENT之一的值。 pg_has_role(user, role, privilege) 描述:指定用户是否有角色的权限。 返回类型:Boolean pg_has_role(role, privilege) 描述:当前用户是否有角色的权限。 返回类型:Boolean 备注:pg_has_role检查用户是否能以特定方式访问一个角色。其参数类似has_table_privilege,除了public不能用做用户名。访问权限类型必须是MEMBER或USAGE的一些组合。 MEMBER表示的是角色中的直接或间接成员关系(也就是SET ROLE的权限),而USAGE表示无需通过SET ROLE也直接拥有角色的使用权限。
  • 会话信息函数 current_catalog 描述:当前数据库的名称(在标准SQL中称"catalog")。 返回值类型:name 示例: 12345 openGauss=# SELECT current_catalog; current_database------------------ openGauss(1 row) current_database() 描述:当前数据库的名称。 返回值类型:name 示例: 12345 openGauss=# SELECT current_database(); current_database------------------ openGauss(1 row) current_query() 描述:由客户端提交的当前执行语句(可能包含多个声明)。 返回值类型:text 示例: 12345 openGauss=# SELECT current_query(); current_query------------------------- SELECT current_query();(1 row) current_schema[()] 描述:当前模式的名称。 返回值类型:name 示例: 12345 openGauss=# SELECT current_schema(); current_schema---------------- public(1 row) 备注:current_schema返回在搜索路径中第一个顺位有效的模式名。(如果搜索路径为空则返回NULL,没有有效的模式名也返回NULL)。如果创建表或者其他命名对象时没有声明目标模式,则将使用这些对象的模式。 current_schemas(Boolean) 描述:搜索路径中的模式名称。 返回值类型:name[] 示例: 12345 openGauss=# SELECT current_schemas(true); current_schemas--------------------- {pg_catalog,public}(1 row) 备注: current_schemas(Boolean)返回搜索路径中所有模式名称的数组。布尔选项决定像pg_catalog这样隐含包含的系统模式是否包含在返回的搜索路径中。 搜索路径可以通过运行时设置更改。命令是: 1 SET search_path TO schema [, schema, ...] current_user 描述:当前执行环境下的用户名。 返回值类型:name 示例: 12345 openGauss=# SELECT current_user; current_user-------------- omm(1 row) 备注:current_user是用于权限检查的用户标识。通常,他表示会话用户,但是可以通过SET ROLE改变他。在函数执行的过程中随着属性SECURITY DEFINER的改变,其值也会改变。 definer_current_user 描述:当前执行环境下的用户名。 返回值类型:name 示例: 12345 openGauss=# SELECT definer_current_user(); definer_current_user---------------------- omm(1 row) pg_current_sessionid() 描述:当前执行环境下的会话ID。 返回值类型:text 示例: 12345 openGauss=# SELECT pg_current_sessionid(); pg_current_sessionid---------------------------- 1579228402.140190434944768(1 row) 备注:pg_current_sessionid()是用于获取当前执行环境下的会话ID。其组成结构为:时间戳.会话ID,当线程池模式开启(enable_thread_pool=on)时,会话ID为SessionID;而线程池模式关闭时,会话ID为ThreadID。 pg_current_sessid 描述:当前执行环境下的会话ID。 返回值类型:text 示例: openGauss=# select pg_current_sessid();pg_current_sessid-------------------140308875015936(1 row) 备注:在线程池模式下获得当前会话的会话ID,非线程池模式下获得当前会话对应的后台线程ID。 pg_current_userid 描述:当前用户ID。 返回值类型:text openGauss=# SELECT pg_current_userid();pg_current_userid-------------------10(1 row) working_version_num() 描述:版本序号信息。返回一个系统兼容性有关的版本序号。 返回值类型:int 示例: 12345 openGauss=# SELECT working_version_num(); working_version_num--------------------- 92231(1 row) tablespace_oid_name() 描述: 根据表空间oid,查找表空间名称。 返回值类型:text 示例: 12345 openGauss=# select tablespace_oid_name(1663); tablespace_oid_name--------------------- pg_default(1 row) inet_client_addr() 描述:连接的远端地址。inet_client_addr返回当前客户端的IP地址。 此函数只有在远程连接模式下有效。 返回值类型:inet 示例: 12345 openGauss=# SELECT inet_client_addr(); inet_client_addr------------------ 10.10.0.50(1 row) inet_client_port() 描述:连接的远端端口。inet_client_port返回当前客户端的端口号。 此函数只有在远程连接模式下有效。 返回值类型:int 示例: 12345 openGauss=# SELECT inet_client_port(); inet_client_port------------------ 33143(1 row) inet_server_addr() 描述:连接的本地地址。inet_server_addr返回服务器接收当前连接用的IP地址。 此函数只有在远程连接模式下有效。 返回值类型:inet 示例: 12345 openGauss=# SELECT inet_server_addr(); inet_server_addr------------------ 10.10.0.13(1 row) inet_server_port() 描述:连接的本地端口。inet_server_port返回接收当前连接的端口号。如果是通过Unix-domain socket连接的,则所有这些函数都返回NULL。 此函数只有在远程连接模式下有效。 返回值类型:int 示例: 12345 openGauss=# SELECT inet_server_port(); inet_server_port------------------ 8000(1 row) pg_backend_pid() 描述:当前会话连接的服务进程的进程ID。 返回值类型:int 示例: 12345 openGauss=# SELECT pg_backend_pid(); pg_backend_pid----------------- 140229352617744(1 row) pg_conf_load_time() 描述:配置加载时间。pg_conf_load_time返回最后加载服务器配置文件的时间戳。 返回值类型:timestamp with time zone 示例: 12345 openGauss=# SELECT pg_conf_load_time(); pg_conf_load_time ------------------------------ 2017-09-01 16:05:23.89868+08(1 row) pg_my_temp_schema() 描述:会话的临时模式的OID,不存在则为0。 返回值类型:oid 示例: 12345 openGauss=# SELECT pg_my_temp_schema(); pg_my_temp_schema ------------------- 0(1 row) 备注:pg_my_temp_schema返回当前会话中临时模式的OID,如果不存在(没有创建临时表)的话则返回0。如果给定的OID是其它会话中临时模式的OID,pg_is_other_temp_schema则返回true。 pg_is_other_temp_schema(oid) 描述:是否为另一个会话的临时模式。 返回值类型:Boolean 示例: 12345 openGauss=# SELECT pg_is_other_temp_schema(25356); pg_is_other_temp_schema------------------------- f(1 row) pg_listening_channels() 描述:会话正在侦听的信道名称。 返回值类型:setof text 示例: 1234 openGauss=# SELECT pg_listening_channels(); pg_listening_channels-----------------------(0 rows) 备注:pg_listening_channels返回当前会话正在侦听的一组信道名称。 pg_postmaster_start_time() 描述:服务器启动时间。pg_postmaster_start_time返回服务器启动时的timestamp with time zone。 返回值类型:timestamp with time zone 示例: 12345 openGauss=# SELECT pg_postmaster_start_time(); pg_postmaster_start_time ------------------------------ 2017-08-30 16:02:54.99854+08(1 row) pg_get_ruledef(rule_oid) 描述:获取规则的CREATE RULE命令。 返回值类型:text 示例: openGauss=# select * from pg_get_ruledef(24828); pg_get_ruledef------------------------------------------------------------------- CREATE RULE t1_ins AS ON INSERT TO t1 DO INSTEAD INSERT INTO t2 (id) VALUES (new.id);(1 row) sessionid2pid() 描述: 从sessionid中得到pid信息(例如,gs_session_stat中sessid列)。 返回值类型: int8 示例: 123456 openGauss=# select sessionid2pid(sessid::cstring) from gs_session_stat limit 2; sessionid2pid----------------- 139973107902208 139973107902208(2 rows) session_context( 'namespace' , 'parameter') 描述:获取并返回指定namespace下参数parameter的值。 返回值类型:VARCHAR 示例: 12345 openGauss=# SELECT session_context('USERENV', 'CURRENT_SCHEMA');session_context ------------------ public(1 row) 备注:当前支持的parameter:current_user, current_schema, client_info, ip_address, sessionid, sid. pg_trigger_depth() 描述:触发器的嵌套层次。 返回值类型:int 示例: 12345 openGauss=# SELECT pg_trigger_depth(); pg_trigger_depth ------------------ 0(1 row) session_user 描述:会话用户名。 返回值类型:name 示例: 12345 openGauss=# SELECT session_user; session_user-------------- omm(1 row) 备注:session_user通常是连接当前数据库的初始用户,不过系统管理员可以用SET SESSION AUTHORIZATION修改这个设置。 user 描述:等价于current_user。 返回值类型:name 示例: 12345 openGauss=# SELECT user; current_user-------------- omm(1 row) getpgusername() 描述:获取数据库用户名。 返回值类型:name 示例: 12345 openGauss=# select getpgusername(); getpgusername --------------- GaussDB_userna(1 row) getdatabaseencoding() 描述:获取数据库编码方式。 返回值类型:name 示例: 12345 openGauss=# select getdatabaseencoding(); getdatabaseencoding --------------------- SQL_ASCII(1 row) version() 描述:版本信息。version返回一个描述服务器版本信息的字符串。 返回值类型:text 示例: openGauss=# select version();version-------------------------------------------------------------------------------------------------------------------------------------------------------------(GaussDB Kernel VxxxRxxxCxx build fab4f5ea) compiled at 2021-10-24 11:58:22 commit 3086 last mr 6592 release(1 row) opengauss_version() 描述:openGauss版本信息。 返回值类型:text 示例: 12345 openGauss=# select opengauss_version(); opengauss_version------------------- 2.0.0(1 row) gs_deployment() 描述:当前系统的部署形态信息。 返回值类型:text 示例: 12345 openGauss=# select gs_deployment(); gs_deployment--------------------- BusinessCentralized(1 row) get_hostname() 描述:返回当前节点的hostname。 返回值类型:text 示例: 12345 openGauss=# SELECT get_hostname(); get_hostname-------------- linux-user(1 row) get_nodename() 描述:返回当前节点的名字。 返回值类型:text 示例: 12345 openGauss=# SELECT get_nodename(); get_nodename-------------- datanode1(1 row) get_schema_oid(cstring) 描述:返回查询schema的oid。 返回值类型:oid 示例: 12345 openGauss=# SELECT get_schema_oid('public'); get_schema_oid---------------- 2200(1 row) get_client_info() 描述:返回客户端信息。 返回值类型:record
  • 搜索表 在不使用索引的情况下也可以进行全文检索。 一个简单查询:将body字段中包含america的每一行打印出来。 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738 openGauss=# DROP SCHEMA IF EXISTS tsearch CASCADE;openGauss=# CREATE SCHEMA tsearch;openGauss=# CREATE TABLE tsearch.pgweb(id int, body text, title text, last_mod_date date);openGauss=# INSERT INTO tsearch.pgweb VALUES(1, 'China, officially the People''s Republic of China (PRC), located in Asia, is the world''s most populous state.', 'China', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(2, 'America is a rock band, formed in England in 1970 by multi-instrumentalists Dewey Bunnell, Dan Peek, and Gerry Beckley.', 'America', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(3, 'England is a country that is part of the United Kingdom. It shares land borders with Scotland to the north and Wales to the west.', 'England', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(4, 'Australia, officially the Commonwealth of Australia, is a country comprising the mainland of the Australian continent, the island of Tasmania, and numerous smaller islands.', 'Australia', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(6, 'Japan is an island country in East Asia.', 'Japan', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(7, 'Germany, officially the Federal Republic of Germany, is a sovereign state and federal parliamentary republic in central-western Europe.', 'Germany', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(8, 'France, is a sovereign state comprising territory in western Europe and several overseas regions and territories.', 'France', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(9, 'Italy officially the Italian Republic, is a unitary parliamentary republic in Europe.', 'Italy', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(10, 'India, officially the Republic of India, is a country in South Asia.', 'India', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(11, 'Brazil, officially the Federative Republic of Brazil, is the largest country in both South America and Latin America.', 'Brazil', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(12, 'Canada is a country in the northern half of North America.', 'Canada', '2010-1-1');openGauss=# INSERT INTO tsearch.pgweb VALUES(13, 'Mexico, officially the United Mexican States, is a federal republic in the southern part of North America.', 'Mexico', '2010-1-1');openGauss=# SELECT id, body, title FROM tsearch.pgweb WHERE to_tsvector('english', body) @@ to_tsquery('english', 'america'); id | body | title ----+-------------------------------------------------------------------------------------------------------------------------+--------- 2 | America is a rock band, formed in England in 1970 by multi-instrumentalists Dewey Bunnell, Dan Peek, and Gerry Beckley. | America 11 | Brazil, officially the Federative Republic of Brazil, is the largest country in both South America and Latin America. | Brazil 12 | Canada is a country in the northern half of North America. | Canada 13 | Mexico, officially the United Mexican States, is a federal republic in the southern part of North America. | Mexico(4 rows) 像America这样的相关词也会被找到,因为这些词都被处理成了相同标准的词条。 上面的查询指定english配置来解析和规范化字符串。当然也可以省略此配置,通过default_text_search_config进行配置设置: 1 2 3 4 5 6 7 8 91011121314 openGauss=# SHOW default_text_search_config; default_text_search_config ---------------------------- pg_catalog.english(1 row)openGauss=# SELECT id, body, title FROM tsearch.pgweb WHERE to_tsvector(body) @@ to_tsquery('america'); id | body | title ----+-------------------------------------------------------------------------------------------------------------------------+--------- 2 | America is a rock band, formed in England in 1970 by multi-instrumentalists Dewey Bunnell, Dan Peek, and Gerry Beckley. | America 11 | Brazil, officially the Federative Republic of Brazil, is the largest country in both South America and Latin America. | Brazil 12 | Canada is a country in the northern half of North America. | Canada 13 | Mexico, officially the United Mexican States, is a federal republic in the southern part of North America. | Mexico(4 rows) 一个复杂查询:检索出在title或者body字段中包含north和america的最近10篇文档: 123456 openGauss=# SELECT title FROM tsearch.pgweb WHERE to_tsvector(title || ' ' || body) @@ to_tsquery('north & america') ORDER BY last_mod_date DESC LIMIT 10; title -------- Canada Mexico(2 rows) 为了清晰,举例中没有调用coalesce函数在两个字段中查找包含NULL的行。 以上例子均在没有索引的情况下进行查询。对于大多数应用程序来说,这个方法很慢。因此除了偶尔的特定搜索,文本搜索在实际使用中通常需要创建索引。 父主题: 表和索引
  • 处理tsvector GaussDB提供了用来操作tsvector类型的函数和操作符。 tsvector || tsvector tsvector连接操作符返回一个新的tsvector类型,它综合了两个tsvector中词素和位置信息,并保留词素的位置信息和权重标签。右侧的tsvector的起始位置位于左侧tsvector的最后位置,因此,新生成的tsvector几乎等同于将两个原始文档字串连接后进行to_tsvector操作。(这个等价是不准确的,因为任何从左边tsvector中删除的停用词都不会影响结果,但是,在使用文本连接时,则会影响词素在右侧tsvector中的位置。) 相较于对文本进行连接后再执行to_tsvector操作,使用tsvector类型进行连接操作的优势在于,可以对文档的不同部分使用不同配置进行解析。因为setweight函数会对给定的tsvector中的语素进行统一设置,如果想要对文档的不同部分设置不同的权重,需要在连接之前对文本进行解析和权重设置。 setweight(vector tsvector, weight "char") returns tsvector setweight返回一个输入tsvector的副本,其中每一个位置都使用给定的权重做了标记。权值可以为A、B、C或D(D是tsvector副本的默认权重,并且不在输出中呈现)。当对tsvector进行连接操作时,这些权重标签将会被保留,文档不同部分以不同的权重进行排序。 权重标签作用于位置,而不是词素。如果传入的tsvector已经被剥离了位置信息,那么setweight函数将什么都不做。 length(vector tsvector) returns integer 返回vector中的词素的数量。 strip(vector tsvector) returns tsvector 返回一个tsvector类型,其中包含输入的tsvector的同义词,但不包含任何位置和权重信息。虽然在相关性排序中,这里返回的tsvector要比未拆分的tsvector的作用小很多,但它通常都比未拆分的tsvector小的多。 父主题: 附加功能
  • 处理查询 GaussDB提供了函数和操作符用来操作tsquery类型的查询。 tsquery && tsquery 返回两个给定查询tsquery的与结果。 tsquery || tsquery 返回两个给定查询tsquery的或结果。 !! tsquery 返回给定查询tsquery的非结果。 numnode(query tsquery) returns integer 返回tsquery中的节点数目(词素加操作符),这个函数在检查查询是否有效(返回值大于0),或者只包含停用词(返回值等于0)时,是有用的。例如: 1 2 3 4 5 6 7 8 91011 openGauss=# SELECT numnode(plainto_tsquery('the any'));NOTICE: text-search query contains only stop words or doesn't contain lexemes, ignoredCONTEXT: referenced column: numnode numnode --------- 0openGauss=# SELECT numnode('foo & bar'::tsquery); numnode--------- 3 querytree(query tsquery) returns text 返回可用于索引搜索的tsquery部分,该函数对于检测非索引查询是有用的(例如只包含停用词或否定项)。例如: 12345 openGauss=# SELECT querytree(to_tsquery('!defined')); querytree ----------- T(1 row) 父主题: 附加功能
  • 内部函数 GaussDB中下列函数使用了内部数据类型,用户无法直接调用,在此章节列出。 选择率计算函数 areajoinsel areasel arraycontjoinsel arraycontsel contjoinsel contsel eqjoinsel eqsel iclikejoinsel iclikesel icnlikejoinsel icnlikesel icregexeqjoinsel icregexeqsel icregexnejoinsel icregexnesel likejoinsel likesel neqjoinsel neqsel nlikejoinsel nlikesel positionjoinsel positionsel regexeqjoinsel regexeqsel regexnejoinsel regexnesel scalargtjoinsel scalargtsel scalarltjoinsel scalarltsel tsmatchjoinsel tsmatchsel - 统计信息收集函数 array_typanalyze range_typanalyze ts_typanalyze local_rto_stat - - 排序内部功能函数 bpchar_sortsupport bytea_sortsupport date_sortsupport numeric_sortsupport timestamp_sortsupport 全文检索内部功能函数 dispell_init dispell_lexize dsimple_init dsimple_lexize dsnowball_init dsnowball_lexize dsynonym_init dsynonym_lexize gtsquery_compress gtsquery_consistent gtsquery_decompress gtsquery_penalty gtsquery_picksplit gtsquery_same gtsquery_union ngram_end ngram_lextype ngram_start pound_end pound_lextype pound_start prsd_end prsd_headline prsd_lextype prsd_start thesaurus_init thesaurus_lexize zhprs_end zhprs_getlexeme zhprs_lextype zhprs_start - - - - 内部类型处理函数 abstimerecv euc_jis_2004_to_utf8 int2recv line_recv oidvectorrecv_extend tidrecv utf8_to_koi8u anyarray_recv euc_jp_to_mic int2vectorrecv lseg_recv path_recv time_recv utf8_to_shift_jis_2004 array_recv euc_jp_to_sjis int4recv macaddr_recv pg_node_tree_recv time_transform utf8_to_sjis ascii_to_mic euc_jp_to_utf8 int8recv mic_to_ascii point_recv timestamp_recv utf8_to_uhc ascii_to_utf8 euc_kr_to_mic internal_out mic_to_big5 poly_recv timestamp_transform utf8_to_win big5_to_euc_tw euc_kr_to_utf8 interval_recv mic_to_euc_cn pound_nexttoken timestamptz_recv uuid_recv big5_to_mic euc_tw_to_big5 interval_transform mic_to_euc_jp prsd_nexttoken timetz_recv varbit_recv big5_to_utf8 euc_tw_to_mic iso_to_koi8r mic_to_euc_kr range_recv tintervalrecv varbit_transform bit_recv euc_tw_to_utf8 iso_to_mic mic_to_euc_tw rawrecv tsqueryrecv varchar_transform boolrecv float4recv iso_to_win1251 mic_to_iso record_recv tsvectorrecv varcharrecv box_recv float8recv iso_to_win866 mic_to_koi8r regclassrecv txid_snapshot_recv void_recv bpcharrecv gb18030_to_utf8 iso8859_1_to_utf8 mic_to_latin1 regconfigrecv uhc_to_utf8 win_to_utf8 btoidsortsupport gbk_to_utf8 iso8859_to_utf8 mic_to_latin2 regdictionaryrecv unknownrecv win1250_to_latin2 bytearecv gin_extract_tsvector johab_to_utf8 mic_to_latin3 regoperatorrecv utf8_to_ascii win1250_to_mic byteawithoutorderwithequalcolrecv gtsvector_compress json_recv mic_to_latin4 regoperrecv utf8_to_big5 win1251_to_iso cash_recv gtsvector_consistent koi8r_to_iso mic_to_sjis regprocedurerecv utf8_to_euc_cn win1251_to_koi8r charrecv gtsvector_decompress koi8r_to_mic mic_to_win1250 regprocrecv utf8_to_euc_jis_2004 win1251_to_mic cidr_recv gtsvector_penalty koi8r_to_utf8 mic_to_win1251 regtyperecv utf8_to_euc_jp win1251_to_win866 cidrecv gtsvector_picksplit koi8r_to_win1251 mic_to_win866 reltimerecv utf8_to_euc_kr win866_to_iso circle_recv gtsvector_same koi8r_to_win866 namerecv shift_jis_2004_to_euc_jis_2004 utf8_to_euc_tw win866_to_koi8r cstring_recv gtsvector_union koi8u_to_utf8 ngram_nexttoken shift_jis_2004_to_utf8 utf8_to_gb18030 win866_to_mic date_recv hll_recv latin1_to_mic numeric_recv sjis_to_euc_jp utf8_to_gbk win866_to_win1251 domain_recv hll_trans_recv latin2_to_mic numeric_transform sjis_to_mic utf8_to_iso8859 xidrecv euc_cn_to_mic hstore_recv latin2_to_win1250 nvarchar2recv sjis_to_utf8 utf8_to_iso8859_1 xidrecv4 euc_cn_to_utf8 inet_recv latin3_to_mic oidrecv smalldatetime_recv utf8_to_johab xml_recv euc_jis_2004_to_shift_jis_2004 int1recv latin4_to_mic oidvectorrecv textrecv utf8_to_koi8r cstore_tid_out i16toi1 int16 int16_bool int16eq int16div int16ge int16gt int16in int16le int16lt int16mi int16mul int16ne int16out int16pl int16recv int16send numeric_bool int2vectorin_extend int2vectorout_extend int2vectorrecv_extend int2vectorsend_extend tdigest_in tdigest_merge tdigest_merge_to_one tdigest_mergep tdigest_out - 聚合操作内部函数 array_agg_finalfn array_agg_transfn bytea_string_agg_finalfn bytea_string_agg_transfn date_list_agg_noarg2_transfn date_list_agg_transfn float4_list_agg_noarg2_transfn float4_list_agg_transfn float8_list_agg_noarg2_transfn float8_list_agg_transfn int2_list_agg_noarg2_transfn int2_list_agg_transfn int4_list_agg_noarg2_transfn int4_list_agg_transfn int8_list_agg_noarg2_transfn int8_list_agg_transfn interval_list_agg_noarg2_transfn interval_list_agg_transfn list_agg_finalfn list_agg_noarg2_transfn list_agg_transfn median_float8_finalfn median_interval_finalfn median_transfn mode_final numeric_list_agg_noarg2_transfn numeric_list_agg_transfn ordered_set_transition percentile_cont_float8_final percentile_cont_interval_final string_agg_finalfn string_agg_transfn timestamp_list_agg_noarg2_transfn timestamp_list_agg_transfn timestamptz_list_agg_noarg2_transfn timestamptz_list_agg_transfn checksumtext_agg_transfn - - - - - 哈希内部功能函数 hashbeginscan hashbuild hashbuildempty hashbulkdelete hashcostestimate hashendscan hashgetbitmap hashgettuple hashinsert hashmarkpos hashmerge hashrescan hashrestrpos hashvacuumcleanup hashvarlena - - - - - - Btree索引内部功能函数 cbtreebuild cbtreecanreturn cbtreecostestimate cbtreegetbitmap cbtreegettuple btbeginscan btbuild btbuildempty btbulkdelete btcanreturn btcostestimate btendscan btfloat4sortsupport btfloat8sortsupport btgetbitmap btgettuple btinsert btint2sortsupport btint4sortsupport btint8sortsupport btmarkpos btmerge btnamesortsupport btrescan btrestrpos bttextsortsupport btvacuumcleanup cbtreeoptions GiST索引内部功能函数 gist_box_compress gist_box_consistent gist_box_decompress gist_box_penalty gist_box_picksplit gist_box_same gist_box_union gist_circle_compress gist_circle_consistent gist_point_compress gist_point_consistent gist_point_distance gist_poly_compress gist_poly_consistent gistbeginscan gistbuild gistbuildempty gistbulkdelete gistcostestimate gistendscan gistgetbitmap gistinsert gistmarkpos gistmerge gistrescan gistrestrpos gistvacuumcleanup range_gist_compress range_gist_decompress range_gist_penalty range_gist_picksplit range_gist_same range_gist_union spg_kd_choose spg_kd_config spg_kd_picksplit spg_quad_choose spg_quad_config spg_quad_inner_consistent spg_quad_leaf_consistent spg_quad_picksplit spg_text_choose spg_text_inner_consistent spg_text_leaf_consistent spg_text_picksplit spgbeginscan spgbuild spgbuildempty spgbulkdelete spgcostestimate spgendscan spggetbitmap spggettuple spginsert spgmarkpos spgmerge spgrestrpos spgvacuumcleanup - - - - - Gin索引内部功能函数 gin_cmp_prefix gin_extract_tsquery gin_tsquery_consistent gin_tsquery_triconsistent ginarrayconsistent ginarrayextract ginarraytriconsistent ginbeginscan ginbuild ginbuildempty ginbulkdelete gincostestimate ginendscan gingetbitmap gininsert ginmarkpos ginmerge ginqueryarrayextract ginrescan ginrestrpos ginvacuumcleanup cginbuild cgingetbitmap - - - - - Psort索引内部函数 psortbuild psortcanreturn psortcostestimate psortgetbitmap psortgettuple Ubtree索引内部函数 ubtbeginscan ubtbuild ubtbuildempty ubtbulkdelete ubtcanreturn ubtcostestimate ubtendscan ubtgetbitmap ubtgettuple ubtinsert ubtmarkpos ubtmerge ubtoptions ubtrescan ubtrestrpos ubtvacuumcleanup - - - - plpgsql内部函数 plpgsql_inline_handler 集合相关内部函数 array_indexby_delete array_indexby_length array_integer_deleteidx array_integer_exists array_integer_first array_integer_last array_integer_next array_integer_prior array_varchar_deleteidx array_varchar_exists array_varchar_first array_varchar_last array_varchar_next array_varchar_prior - - - - 外表相关内部函数 dist_fdw_handler roach_handler streaming_fdw_handler dist_fdw_validator file_fdw_handler file_fdw_validator log_fdw_handler 主DN远程读取备DN数据页辅助函数 gs_read_block_from_remote用于读取非段页式表文件的页面。默认只有初始化用户可以查看,其余用户需要赋权后才可以使用。 gs_read_segment_block_from_remote用于读取段页式表文件的页面。默认只有初始化用户可以查看,其余用户需要赋权后才可以使用。 主DN远程读取备DN数据文件辅助函数 gs_read_file_from_remote用于读取指定的文件。gs_repair_file利用gs_read_file_size_from_remote函数获取文件大小后,依赖这个函数将远端文件逐段读取。默认只有初始化用户可以查看,其余用户需要赋权后才可以使用。 gs_read_file_size_from_remote用于读取指定文件的大小。用于读取指定文件的大小,gs_repair_file函数修复文件时,要先获取远端关于这个文件的大小,用于校验本地文件缺失的文件信息,然后将缺失的文件逐个修复。默认只有初始化用户可以查看,其余用户需要赋权后才可以使用。 AI特性函数 create_snapshot create_snapshot_internal prepare_snapshot_internal prepare_snapshot manage_snapshot_internal archive_snapshot publish_snapshot purge_snapshot_internal purge_snapshot sample_snapshot - - - - PKG_SERVICE函数 isubmit_on_nodes submit_on_nodes - - - - - 其他函数 to_tsvector_for_batch value_of_percentile disable_conn bind_variable job_update job_cancel job_finish similar_escape table_skewness (不可用) timetz_text time_text reltime_text abstime_text _pg_keysequal analyze_query (不可用) analyze_workload (不可用) ssign_table_type gs_comm_proxy_thread_status gs_txid_oldestxmin pg_cancel_session pg_stat_segment_space_info remote_segment_space_info set_cost_params set_weight_params start_collect_workload tdigest_in tdigest_merge tdigest_merge_to_one tdigest_mergep tdigest_out pg_get_delta_info - - - - 视图相关引用函数 adm_hist_sqlstat_func adm_hist_sqlstat_idlog_func 父主题: 函数和操作符
  • 词典概述 词典用于定义停用词(stop words),即全文检索时不搜索哪些词。 词典还可以用于对同一词的不同形式进行规范化,这样同一个词的不同派生形式都可以进行匹配。规范化后的词称为词位(lexeme)。 除了提高检索质量外,词的规范化和删除停用词可以减少文档tsvector格式的大小, 从而提高性能。词的规范化和删除停用词并不总是具有语言学意义,用户可以根据应用环境在词典定义文件中自定义规范化和删除规则。 一个词典是一个程序,接收标记(token)作为输入,并返回: 如果token在词典中已知,返回对应lexeme数组(注意,一个标记可能对应多个lexeme)。 一个lexeme。一个新token会代替输入token被传递给后继词典(当前词典可被称为过滤词典)。 如果token在词典中已知,但它是一个停用词,返回空数组。 如果词典不能识别输入的token,返回NULL。 GaussDB提供了多种语言的预定义字典,同时提供了五种预定义的词典模板,分别是Simple,Synonym,Thesaurus,Ispell,和Snowball,可用于创建自定义参数的新词典。 在使用全文检索时,建议用户: 可以在文本搜索配置中定义一个解析器,以及一组用于处理该解析器的输出标记词典。对于解析器返回的每个标记类型,可以在配置中指定不同的词典列表进行处理。当解析器输出一种类型的标记后,在对应列表的每个字典中会查阅该标记,直到某个词典识别它。如果它被识别为一个停用词, 或者没有任何词典识别,该token将被丢弃,即不被索引或检索到。通常情况下,第一个返回非空结果的词典决定了最终结果,后继词典将不会继续处理。但是一个过滤类型的词典可以依据规则替换输入token,然后将替换后的token传递给后继词典进行处理。 配置字典列表的一般规则是,第一个位置放置一个应用范围最小的、最具体化定义的词典,其次是更一般化定义的词典, 最后是一个普适定义的词典,比如Snowball词干词典或Simple词典。在下面例子中,对于一个针对天文学的文本搜索配置astro_en,可以定义标记类型asciiword(ASCII词)对应的词典列表为:天文术语的Synonym同义词词典, Ispell英语词典和Snowball 英语词干词典。 12 openGauss=# ALTER TEXT SEARCH CONFIGURATION astro_en ADD MAPPING FOR asciiword WITH astro_syn, english_ispell, english_stem; 过滤类型的词典可以放置在词典列表中除去末尾的任何地方,放置在末尾时是无效的。使用这些词典对标记进行部分规范化,可以有效简化后继词典的处理。 父主题: 词典
  • 停用词 停用词是很常见的词,几乎出现在每一个文档中,并且没有区分值。因此,在全文搜索的语境下可忽视它们。停用词处理逻辑和词典类型相关。例如,Ispell词典会先对标记进行规范化,然后再查看停用词表,而Snowball词典会最先检查输入标记是否为停用词。 例如,每个英文文本包含像a和the的单词,因此没必要将它们存储在索引中。然而,停用词影响tsvector中的位置,同时位置也会影响相关度: 1234 openGauss=# SELECT to_tsvector('english','in the list of stop words'); to_tsvector---------------------------- 'list':3 'stop':5 'word':6 位置1、2、4是停用词,所以不显示。为包含和不包含停用词的文档计算出的排序是完全不同的: 123456789 openGauss=# SELECT ts_rank_cd (to_tsvector('english','in the list of stop words'), to_tsquery('list & stop')); ts_rank_cd------------ .05openGauss=# SELECT ts_rank_cd (to_tsvector('english','list stop words'), to_tsquery('list & stop')); ts_rank_cd------------ .1 父主题: 词典
  • 排序查询结果 排序试图针对特定查询衡量文档的相关度,从而将众多的匹配文档中相关度最高的文档排在最前。GaussDB提供了两个预置的排序函数。函数考虑了词法,距离,和结构信息;也就是,他们考虑查询词在文档中出现的频率、紧密程度、以及他们出现的地方在文档中的重要性。然而,相关性的概念是模糊的,并且是跟应用强相关的。不同的应用程序可能需要额外的信息来排序,比如,文档的修改时间,内置的排序函数等。也可以开发自己的排序函数或者采用附加因素组合这些排序函数的结果来满足特定需求。 两个预置的排序函数: 1 ts_rank([ weights float4[], ] vector tsvector, query tsquery [, normalization integer ]) returns float4 基于词素匹配率对vector进行排序: 1 ts_rank_cd([ weights float4[], ] vector tsvector, query tsquery [, normalization integer ]) returns float4 该函数需要位置信息的输入。因此它不能在“剥离”tsvector值的情况下运行—它将总是返回零。 对于这两个函数,可选的weights参数提供给词加权重的能力,词的权重大小取决于所加的权值。权重阵列指定在排序时为每类词汇加多大的权重。 {D-weight, C-weight, B-weight, A-weight} 如果没有提供weights,则使用缺省值:{0.1, 0.2, 0.4, 1.0}。 通常的权重是用来标记文档特殊领域的词,如标题或最初的摘要,所以相对于文章主体中的词它们有着更高或更低的重要性。 由于较长的文档有更多的机会包含查询词,因此有必要考虑文档的大小。例如,包含有5个搜索词的一百字文档比包含有5个搜索词的一千字文档相关性更高。两个预置的排序函数都采用了一个整型的标准化选项来定义文档长度是否影响排序及如何影响。这个整型选项控制多个行为,所以它是一个屏蔽字:可以使用|指定一个或多个行为(例如,2|4)。 0(缺省)表示:跟长度大小没有关系 1 表示:排名(rank)除以(文档长度的对数+1) 2表示:排名除以文档的长度 4表示:排名除以两个扩展词间的调和平均距离。只能使用ts_rank_cd实现 8表示:排名除以文档中单独词的数量 16表示:排名除以单独词数量的对数+1 32表示:排名除以排名本身+1 当指定多个标志位时,会按照所列的顺序依次进行转换。 需要特别注意的是,排序函数不使用任何全局信息,所以不可能产生一个某些情况下需要的1%或100%的理想标准值。标准化选项32 (rank/(rank+1))可用于所有规模的从零到一之间的排序,当然,这只是一个表面变化;它不会影响搜索结果的排序。 下面是一个例子,仅选择排名前十的匹配: 1 2 3 4 5 6 7 8 9101112 openGauss=# SELECT id, title, ts_rank_cd(to_tsvector(body), query) AS rank FROM tsearch.pgweb, to_tsquery('america') query WHERE query @@ to_tsvector(body) ORDER BY rank DESC LIMIT 10; id | title | rank ----+---------+------ 2 | America | .1 11 | Brazil | .2 12 | Canada | .1 13 | Mexico | .1(4 rows) 这是使用标准化排序的相同例子: 1 2 3 4 5 6 7 8 9101112 openGauss=# SELECT id, title, ts_rank_cd(to_tsvector(body), query, 32 /* rank/(rank+1) */ ) AS rank FROM tsearch.pgweb, to_tsquery('america') query WHERE query @@ to_tsvector(body) ORDER BY rank DESC LIMIT 10; id | title | rank ----+---------+---------- 2 | America | .0909091 11 | Brazil | .166667 12 | Canada | .0909091 13 | Mexico | .0909091(4 rows) 下面是使用中文分词法排序查询的例子: 1 2 3 4 5 6 7 8 910111213141516171819 openGauss=# CREATE TABLE tsearch.ts_ngram(id int, body text);openGauss=# INSERT INTO tsearch.ts_ngram VALUES(1, '中文');openGauss=# INSERT INTO tsearch.ts_ngram VALUES(2, '中文检索');openGauss=# INSERT INTO tsearch.ts_ngram VALUES(3, '检索中文');--精确匹配openGauss=# SELECT id, body, ts_rank_cd(to_tsvector('ngram',body), query) AS rank FROM tsearch.ts_ngram, to_tsquery('中文') query WHERE query @@ to_tsvector(body); id | body | rank ----+------+------ 1 | 中文 | .1(1 row)--模糊匹配openGauss=# SELECT id, body, ts_rank_cd(to_tsvector('ngram',body), query) AS rank FROM tsearch.ts_ngram, to_tsquery('中文') query WHERE query @@ to_tsvector('ngram',body); id | body | rank ----+----------+------ 1 | 中文 | .1 2 | 中文检索 | .1 3 | 检索中文 | .1(3 rows) 排序要遍历每个匹配的tsvector,因此资源消耗多,可能会因为I/O限制导致排序慢。可是这是很难避免的,因为实际查询中通常会有大量的匹配。 父主题: 控制文本搜索
  • Snowball词典 Snowball词典模板支持词干分析词典,基于Martin Porter的Snowball项目,内置有许多语言的词干分析算法。GaussDB中预定义有多种语言的Snowball词典,可通过系统表PG_TS_DICT查看预定义的词干分析词典以及支持的语言词干分析算法。 无论是否可以简化,Snowball词典将标示所有输入为已识别,因此它应当被放置在词典列表的最后。把Snowball词典放在任何其他词典前面会导致后继词典失效,因为输入token不会通过Snowball词典进入到下一个词典。 关于Snowball词典的语法,请参见CREATE TEXT SEARCH DICTIONARY。 父主题: 词典
  • 注意事项 大多数词典的功能依赖于词典定义文件,词典定义文件名仅支持小写字母、数字、下划线组合。 临时模式pg_temp下不允许创建词典。 词典定义文件的字符集编码必须为UTF-8格式。实际应用时,如果与数据库的字符编码格式不一致,在读入词典定义文件时会进行编码转换。 通常情况下,每个session仅读取词典定义文件一次,当且仅当在第一次使用该词典时。需要修改词典文件时,可通过ALTER TEXT SEARCH DICTIONARY命令进行词典定义文件的更新和重新加载。
  • 操作步骤 创建Simple词典。 1234 openGauss=# CREATE TEXT SEARCH DICTIONARY public.simple_dict ( TEMPLATE = pg_catalog.simple, STOPWORDS = english); 其中,停用词表文件全名为english.stop。关于创建simple词典的语法和更多参数,请参见CREATE TEXT SEARCH DICTIONARY。 使用Simple词典。 1 2 3 4 5 6 7 8 91011 openGauss=# SELECT ts_lexize('public.simple_dict','YeS'); ts_lexize ----------- {yes}(1 row)openGauss=# SELECT ts_lexize('public.simple_dict','The'); ts_lexize ----------- {}(1 row) 设置参数ACCEPT=false,使Simple词典返回NULL,而不是返回非停用词的小写形式。 1 2 3 4 5 6 7 8 910111213 openGauss=# ALTER TEXT SEARCH DICTIONARY public.simple_dict ( Accept = false );ALTER TEXT SEARCH DICTIONARYopenGauss=# SELECT ts_lexize('public.simple_dict','YeS'); ts_lexize -----------(1 row)openGauss=# SELECT ts_lexize('public.simple_dict','The'); ts_lexize ----------- {}(1 row)
  • 操作步骤 获取词典定义文件和词缀文件。 用户可以使用开源词典,直接获取的开源词典后缀名可能为.aff和.dic,此时需要将扩展名改为.affix和.dict。此外,对于某些词典文件,还需要使用下面的命令把字符转换成 UTF-8 编码,比如挪威语词典: 12 iconv -f ISO_8859-1 -t UTF-8 -o nn_no.affix nn_NO.aff iconv -f ISO_8859-1 -t UTF-8 -o nn_no.dict nn_NO.dic 创建Ispell词典。 123456 openGauss=# CREATE TEXT SEARCH DICTIONARY norwegian_ispell ( TEMPLATE = ispell, DictFile = nn_no, AffFile = nn_no, FilePath = 'file:///home/dicts'); 其中,词典文件全名为nn_no.dict和nn_no.affix,所在目录为当前连接数据库主节点的/home/dicts/下 。关于创建词典的语法和更多参数,请参见CREATE TEXT SEARCH DICTIONARY。 使用Ispell词典进行复合词拆分。 12345 openGauss=# SELECT ts_lexize('norwegian_ispell', 'sjokoladefabrikk'); ts_lexize --------------------- {sjokolade,fabrikk}(1 row) MySpell不支持复合词,Hunspell对复合词有较好的支持。GaussDB仅支持Hunspell中基本的复合词操作。通常情况下,Ispell词典能够识别的词是一个有限集合,其后应该配置一个更广义的词典,例如一个可以识别所有词的Snowball词典。
  • 操作步骤 创建一个名为thesaurus_astro的TZ词典。 以一个简单的天文学词典thesaurus_astro为例,其中定义了两组天文短语及其同义词如下: 12 supernovae stars : sn crab nebulae : crab 执行如下语句创建TZ词典: 123456 openGauss=# CREATE TEXT SEARCH DICTIONARY thesaurus_astro ( TEMPLATE = thesaurus, DictFile = thesaurus_astro, Dictionary = pg_catalog.english_stem, FILEPATH = 'file:///home/dicts/'); 其中,词典定义文件全名为thesaurus_astro.ths,所在目录为当前连接数据库主节点的/home/dicts/下 。子词典pg_catalog.english_stem是预定义的Snowball类型的英语词干词典,用于规范化输入词,子词典自身相关配置(例如停用词等)不在此处显示。关于创建词典的语法和更多参数,请参见CREATE TEXT SEARCH DICTIONARY。 创建词典后,将其绑定到对应文本搜索配置中需要处理的token类型上: 123 openGauss=# ALTER TEXT SEARCH CONFIGURATION russian ALTER MAPPING FOR asciiword, asciihword, hword_asciipart WITH thesaurus_astro, english_stem; 使用TZ词典。 测试TZ词典。 ts_lexize函数对于测试TZ词典作用不大,因为该函数是按照单个token处理输入。可以使用plainto_tsquery、to_tsvector、to_tsquery函数测试TZ词典,这些函数能够将输入分解成多个token(to_tsquery函数需要将输入加上引号)。 1 2 3 4 5 6 7 8 91011121314151617 openGauss=# SELECT plainto_tsquery('russian','supernova star'); plainto_tsquery ----------------- 'sn'(1 row)openGauss=# SELECT to_tsvector('russian','supernova star'); to_tsvector ------------- 'sn':1(1 row)openGauss=# SELECT to_tsquery('russian','''supernova star'''); to_tsquery ------------ 'sn'(1 row) 其中,supernova star匹配了词典thesaurus_astro定义中的supernovae stars,这是因为在thesaurus_astro词典定义中指定了Snowball类型的子词典english_stem,该词典移除了e和s。 如果同时需要索引原始短语,只要将其同时放置在词典定义文件中对应定义的右侧即可,如下: 1 2 3 4 5 6 7 8 91011 supernovae stars : sn supernovae starsopenGauss=# ALTER TEXT SEARCH DICTIONARY thesaurus_astro ( DictFile = thesaurus_astro, FILEPATH = 'file:///home/dicts/');openGauss=# SELECT plainto_tsquery('russian','supernova star'); plainto_tsquery ----------------------------- 'sn' & 'supernova' & 'star'(1 row)
  • 注意事项 由于TZ词典需要识别短语,所以在处理过程中必须保存当前状态并与解析器进行交互,以决定是否处理下一个token或是结束当前识别。此外,TZ词典配置时需谨慎,如果设置TZ词典仅处理asciiword类型的token,则类似one 7的分类词典定义将不会生效,因为uint类型的token不会传给TZ词典处理。 在索引期间要用到分类词典,因此分类词典参数中的任何变化都要求重新索引。对于其他大多数类型的词典来说,类似添加或删除停用词这种修改并不需要强制重新索引。
  • 词典测试 函数ts_lexize用于进行词典测试。 ts_lexize(dict regdictionary, token text) returns text[]如果输入的token可以被词典识别,那么ts_lexize返回词素的数组;如果token可以被词典识别到它是一个停用词,则返回空数组;如果是一个不可识别的词则返回NULL。 比如: 123456789 openGauss=# SELECT ts_lexize('english_stem', 'stars'); ts_lexize----------- {star}openGauss=# SELECT ts_lexize('english_stem', 'a'); ts_lexize----------- {} ts_lexize函数支持单一token,不支持文本。 父主题: 测试和调试文本搜索
  • 示例 Synonym词典可用于解决语言学相关问题,例如,为避免使单词"Paris"变成"pari",可在Synonym词典文件中定义一行"Paris paris",并将该词典放置在预定义的english_stem词典之前。 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041 openGauss=# SELECT * FROM ts_debug('english', 'Paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+----------------+--------------+--------- asciiword | Word, all ASCII | Paris | {english_stem} | english_stem | {pari}(1 row)openGauss=# CREATE TEXT SEARCH DICTIONARY my_synonym ( TEMPLATE = synonym, SYNONYMS = my_synonyms, FILEPATH = 'file:///home/dicts/' );openGauss=# ALTER TEXT SEARCH CONFIGURATION english ALTER MAPPING FOR asciiword WITH my_synonym, english_stem;openGauss=# SELECT * FROM ts_debug('english', 'Paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+---------------------------+------------+--------- asciiword | Word, all ASCII | Paris | {my_synonym,english_stem} | my_synonym | {paris}(1 row)openGauss=# SELECT * FROM ts_debug('english', 'paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+---------------------------+------------+--------- asciiword | Word, all ASCII | Paris | {my_synonym,english_stem} | my_synonym | {paris}(1 row)openGauss=# ALTER TEXT SEARCH DICTIONARY my_synonym ( CASESENSITIVE=true);openGauss=# SELECT * FROM ts_debug('english', 'Paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+---------------------------+------------+--------- asciiword | Word, all ASCII | Paris | {my_synonym,english_stem} | my_synonym | {paris}(1 row)openGauss=# SELECT * FROM ts_debug('english', 'paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+---------------------------+------------+--------- asciiword | Word, all ASCII | Paris | {my_synonym,english_stem} | my_synonym | {pari}(1 row) 其中,同义词词典文件全名为my_synonyms.syn,所在目录为当前连接数据库主节点的/home/dicts/下。关于创建词典的语法和更多参数,请参见ALTER TEXT SEARCH DICTIONARY。 星号(*)可用于词典文件中的同义词结尾,表示该同义词是一个前缀。在to_tsvector()中该星号将被忽略,但在to_tsquery()中会匹配该前缀并对应输出结果(参照处理查询一节)。 假设词典文件synonym_sample.syn内容如下: 12345 postgres pgsqlpostgresql pgsql postgre pgsql gogle googl indices index* 创建并使用词典: 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738 openGauss=# CREATE TEXT SEARCH DICTIONARY syn ( TEMPLATE = synonym, SYNONYMS = synonym_sample);openGauss=# SELECT ts_lexize('syn','indices'); ts_lexize ----------- {index}(1 row)openGauss=# CREATE TEXT SEARCH CONFIGURATION tst (copy=simple);openGauss=# ALTER TEXT SEARCH CONFIGURATION tst ALTER MAPPING FOR asciiword WITH syn;openGauss=# SELECT to_tsvector('tst','indices'); to_tsvector ------------- 'index':1(1 row)openGauss=# SELECT to_tsquery('tst','indices'); to_tsquery ------------ 'index':*(1 row)openGauss=# SELECT 'indexes are very useful'::tsvector; tsvector --------------------------------- 'are' 'indexes' 'useful' 'very'(1 row)openGauss=# SELECT 'indexes are very useful'::tsvector @@ to_tsquery('tst','indices'); ?column? ---------- t(1 row)
  • 操作步骤 创建一个文本搜索配置ts_conf,复制预定义的文本搜索配置english。 12 openGauss=# CREATE TEXT SEARCH CONFIGURATION ts_conf ( COPY = pg_catalog.english );CREATE TEXT SEARCH CONFIGURATION 创建Synonym词典。 假设同义词词典定义文件pg_dict.syn内容如下: 123 postgres pg pgsql pg postgresql pg 执行如下语句创建Synonym词典: 12345 openGauss=# CREATE TEXT SEARCH DICTIONARY pg_dict ( TEMPLATE = synonym, SYNONYMS = pg_dict, FILEPATH = 'file:///home/dicts' ); 创建一个Ispell词典english_ispell(词典定义文件来自开源词典)。 1234567 openGauss=# CREATE TEXT SEARCH DICTIONARY english_ispell ( TEMPLATE = ispell, DictFile = english, AffFile = english, StopWords = english, FILEPATH = 'file:///home/dicts' ); 设置文本搜索配置ts_conf,修改某些类型的token对应的词典列表。关于token类型的详细信息,请参见解析器。 1234 openGauss=# ALTER TEXT SEARCH CONFIGURATION ts_conf ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part WITH pg_dict, english_ispell, english_stem; 在文本搜索配置中,选择设置不索引或搜索某些token类型。 12 openGauss=# ALTER TEXT SEARCH CONFIGURATION ts_conf DROP MAPPING FOR email, url, url_path, sfloat, float; 使用文本检索调测函数ts_debug()对所创建的词典配置ts_conf进行测试。 12345 openGauss=# SELECT * FROM ts_debug('ts_conf', 'PostgreSQL, the highly scalable, SQL compliant, open source object-relationaldatabase management system, is now undergoing beta testing of the nextversion of our software.'); 可以设置当前session使用ts_conf作为默认的文本搜索配置。此设置仅在当前session有效。 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627 openGauss=# \dF+ ts_conf Text search configuration "public.ts_conf"Parser: "pg_catalog.default" Token | Dictionaries -----------------+------------------------------------- asciihword | pg_dict,english_ispell,english_stem asciiword | pg_dict,english_ispell,english_stem file | simple host | simple hword | pg_dict,english_ispell,english_stem hword_asciipart | pg_dict,english_ispell,english_stem hword_numpart | simple hword_part | pg_dict,english_ispell,english_stem int | simple numhword | simple numword | simple uint | simple version | simple word | pg_dict,english_ispell,english_stemopenGauss=# SET default_text_search_config = 'public.ts_conf';SETopenGauss=# SHOW default_text_search_config; default_text_search_config ---------------------------- public.ts_conf(1 row)
  • 解析器测试 函数ts_parse可以直接测试文本搜索解析器。 12 ts_parse(parser_name text, document text, OUT tokid integer, OUT token text) returns setof record ts_parse解析指定的document并返回一系列的记录,一条记录代表一个解析生成的token。每条记录包括标识token类型的tokid,及token文本。例如: 1 2 3 4 5 6 7 8 910 openGauss=# SELECT * FROM ts_parse('default', '123 - a number'); tokid | token-------+-------- 22 | 123 12 | 12 | - 1 | a 12 | 1 | number(6 rows) 函数ts_token_type返回指定解析器的token类型及其描述信息。 12 ts_token_type(parser_name text, OUT tokid integer, OUT alias text, OUT description text) returns setof record ts_token_type返回一个表,这个表描述了指定解析器可以识别的每种token类型。对于每个token类型,表中给出了整数类型的tokid--用于解析器标记对应的token类型;alias——命名分词器命令中的token类型;及简单描述。比如: 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627 openGauss=# SELECT * FROM ts_token_type('default'); tokid | alias | description -------+-----------------+------------------------------------------ 1 | asciiword | Word, all ASCII 2 | word | Word, all letters 3 | numword | Word, letters and digits 4 | email | Email address 5 | url | URL 6 | host | Host 7 | sfloat | Scientific notation 8 | version | Version number 9 | hword_numpart | Hyphenated word part, letters and digits 10 | hword_part | Hyphenated word part, all letters 11 | hword_asciipart | Hyphenated word part, all ASCII 12 | blank | Space symbols 13 | tag | XML tag 14 | protocol | Protocol head 15 | numhword | Hyphenated word, letters and digits 16 | asciihword | Hyphenated word, all ASCII 17 | hword | Hyphenated word, all letters 18 | url_path | URL path 19 | file | File or path name 20 | float | Decimal notation 21 | int | Signed integer 22 | uint | Unsigned integer 23 | entity | XML entity(23 rows) 父主题: 测试和调试文本搜索
  • 示例 --创建表customer_demographics_t1。openGauss=# CREATE TABLE customer_demographics_t1( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER)WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE);--插入记录。openGauss=# INSERT INTO customer_demographics_t1 VALUES(1920801,'M', 'U', 'DOCTOR DEGREE', 200, 'GOOD', 1, 0,0);--开启事务。openGauss=# START TRANSACTION;--更新字段值。openGauss=# UPDATE customer_demographics_t1 SET cd_education_status= 'Unknown';--终止事务,上面所执行的更新会被撤销掉。openGauss=# ABORT; --查询数据。openGauss=# SELECT * FROM customer_demographics_t1 WHERE cd_demo_sk = 1920801;cd_demo_sk | cd_gender | cd_marital_status | cd_education_status | cd_purchase_estimate | cd_credit_rating | cd_dep_count | cd_dep_employed_count | cd_dep_college_count ------------+-----------+-------------------+----------------------+----------------------+------------------+--------------+-----------------------+---------------------- 1920801 | M | U | DOCTOR DEGREE | 200 | GOOD | 1 | 0 | 0(1 row)--删除表。openGauss=# DROP TABLE customer_demographics_t1;
  • 注意事项 要使用 ALTER AGGREGATE ,你必须是该聚合函数的所有者。 要改变一个聚合函数的模式,你必须在新模式上有 CREATE 权限。 要改变所有者,你必须是新所有角色的一个直接或间接成员,并且该角色必须在聚合函数的模式上有 CREATE 权限。(这些限制强制了修改该所有者不会做任何通过删除和重建聚合函数不能做的事情。不过,具有SYSADMIN权限用户可以用任何方法任意更改聚合函数的所属关系)。
  • 示例 把一个接受integer 类型参数的聚合函数myavg重命名为 my_average : ALTER AGGREGATE myavg(integer) RENAME TO my_average; 把一个接受integer 类型参数的聚合函数myavg的所有者改为joe : ALTER AGGREGATE myavg(integer) OWNER TO joe; 把一个接受integer 类型参数的聚合函数myavg移动到模式myschema里: ALTER AGGREGATE myavg(integer) SET SCHEMA myschema;
  • 参数说明 policy_name 审计策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 DDL 指的是针对数据库执行如下操作时进行审计,目前支持:CREATE、ALTER、DROP、ANALYZE、COMMENT、GRANT、REVOKE、SET、SHOW、LOGIN_ANY、LOGIN_FAILURE、LOGIN_SUCCESS、LOGOUT。 ALL 指的是上述DDL支持的所有对数据库的操作。 DML 指的是针对数据库执行如下操作时进行审计,目前支持:SELECT、COPY、DEALLOCATE、DELETE、EXECUTE、INSERT、PREPARE、REINDEX、TRUNCATE、UPDATE。 FILTER_TYPE 指定审计策略的过滤信息,过滤类型包括:IP、ROLES、APP。 filter_value 指具体过滤信息内容。 policy_comments 用于记录策略相关的描述信息。 ENABLE|DISABLE 可以打开或关闭统一审计策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。
共100000条