华为云用户手册

  • 字符串函数 这些函数假定输入字符串包含有效的UTF-8编码的Unicode代码点。不会显式检查UTF-8数据是否有效,对于无效的UTF-8数据,函数可能会返回错误的结果。可以使用from_utf8来更正无效的UTF-8数据。 此外,这些函数对Unicode代码点进行运算,而不是对用户可见的字符(或字形群集)进行运算。某些语言将多个代码点组合成单个用户感观字符(这是语言书写系统的基本单位),但是函数会将每个代码点视为单独的单位。 lower和upper函数不执行某些语言所需的区域设置相关、上下文相关或一对多映射。 chr(n) → varchar 描述:返回Unicode编码值为n的字符值。 select chr(100); --d char_length(string) → bigint 参考length(string) character_length(string) → bigint 参考length(string) codepoint(string) → integer 描述:返回单个字符对应的Unicode编码。 select codepoint('d'); --100 concat(string1, string2) → varchar 描述:字符串连接。 select concat('hello','world'); -- helloworld concat_ws(string0, string1, ..., stringN) → varchar 描述:将string1、string2、...,stringN,以string0作为分隔符串联成一个字符串。如果string0为null,则返回值为null。分隔符后的参数如果是NULL值,将会被跳过。 select concat_ws(',','hello','world'); -- hello,world select concat_ws(NULL,'def'); --NULL select concat_ws(',','hello',NULL,'world'); -- hello,world select concat_ws(',','hello','','world'); -- hello,,world concat_ws(string0, array(varchar)) → varchar 描述:将数组中的元素以string0为分隔符进行串联。如果string0为null,则返回值为null。数组中的任何null值都将被跳过。 select concat_ws(NULL,ARRAY['abc']);--NULL select concat_ws(',',ARRAY['abc',NULL,NULL,'xyz']); -- abc,xyz select concat_ws(',',ARRAY['hello','world']); -- hello,world decode(binary bin, string charset) →varchar 描述:根据给定的字符集将第一个参数编码为字符串,支持的字符集包括('UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'),当第一个参数为null,将返回null。 select decode(X'70 61 6e 64 61','UTF-8'); _col0 ------- panda (1 row) select decode(X'00 70 00 61 00 6e 00 64 00 61','UTF-16BE'); _col0 ------- panda (1 row) encode(string str, string charset) →binary 描述:字符串按照给定的字符集进行编码。 select encode('panda','UTF-8'); _col0 ---------------- 70 61 6e 64 61 (1 row) find_in_set (string str, string strList) →int 描述:返回str在逗号分隔的strList中第一次出现的位置。当有参数为null时,返回值也为null。 select find_in_set('ab', 'abc,b,ab,c,def'); -- 3 format_number(number x, int d) →string 描述:将数字x格式化为'#,###,###.##',保留d位小数,以字符串的形式返回结果。 select format_number(541211.212,2); -- 541,211.21 format(format,args...) → varchar 描述:参见Format。 locate(string substr, string str, int pos]) →int 描述:返回子串在字符串的第pos位后第一次出现的位置。没有满足条件的返回0。 select locate('aaa','bbaaaaa',6);-- 0 select locate('aaa','bbaaaaa',1);-- 3 select locate('aaa','bbaaaaa',4);-- 4 length(string) → bigint 描述:返回字符串的长度。 select length('hello');-- 5 levenshtein_distance(string1, string2) → bigint 描述:计算string1和string2的Levenshtein距离,即将string转为string2所需要的单字符编辑(包括插入、删除或替换)最少次数。 select levenshtein_distance('helo word','hello,world'); -- 3 hamming_distance(string1, string2) → bigint 描述:返回字符串1和字符串2的汉明距离,即对应位置字符不同的数量。 请注意,两个字符串的长度必须相同。 select hamming_distance('abcde','edcba');-- 4 instr(string,substring) → bigint 描述:查找substring 在string中首次出现的位置。 select instr('abcde', 'cd');--3 levenshtein(string1, string2) → bigint 参考levenshtein_distance(string1, string2) levenshtein_distance(string1, string2) → bigint 描述:返回字符串1和字符串2的Levenshtein编辑距离,即将字符串1更改为字符串2所需的最小单字符编辑(插入,删除或替换)次数。 select levenshtein_distance('apple','epplea');-- 2 lower(string) → varchar 描述:将字符转换为小写。 select lower('HELLo!');-- hello! lcase(string A) → varchar 描述:同lower(string)。 ltrim(string) → varchar 描述:去掉字符串开头的空格。 select ltrim(' hello');-- hello lpad(string, size, padstring) → varchar 描述:右填充字符串以使用padstring调整字符大小。如果size小于字符串的长度,则结果将被截断为size个字符。大小不能为负,并且填充字符串必须为非空。 select lpad('myk',5,'dog'); -- domyk
  • 操作场景 用户可以根据业务需要,使用集群客户端创建Kafka Topic。启用Kerberos认证的集群,需要拥有管理Kafka主题的权限。也可以通过KafkaUI修改Topic Configs。 安全模式下,KafkaUI对修改Topic Configs场景,需保证KafkaUI登录用户属于“kafkaadmin”用户组或者单独给用户授予对应操作权限,否则将会鉴权失败。 非安全模式下,KafkaUI对所有操作不作鉴权处理。
  • 示例 CREATE SCHEMA web; DESCRIBE SCHEMA web; Describe Schema ------------------------------------------------------------------------- web hdfs://hacluster/user/hive/warehouse/web.db admintest USER (1 row)
  • 示例 describe formatted show_table1 a; Describe Formatted Column ------------------------------ col_name a data_type integer min max num_nulls distinct_count 0 avg_col_len max_col_len num_trues num_falses comment (1 row)
  • 描述 返回表的近似统计信息。 返回每一列的统计信息。 列 描述 column_name 列名(汇总行为NULL) data_size 列中所有值的总大小(以字节为单位) distinct_values_count 列中不同值的数量 nulls_fraction 列中值为NULL的部分 row_count 行数(仅针对摘要行返回) low_value 在此列中找到的最小值(仅对于某些类型) high_value 在此列中找到的最大值(仅适用于某些类型)
  • 示例 SHOW STATS FOR orders; SHOW STATS FOR (SELECT * FROM orders); 在 Analyze nation表之前: SHOW STATS FOR nation; column_name | data_size | distinct_values_count | nulls_fraction | row_count | low_value | high_value -------------|-----------|-----------------------|----------------|-----------|-----------|------------ name | NULL | NULL | NULL | NULL | NULL | NULL regionkey | NULL | NULL | NULL | NULL | NULL | NULL NULL | NULL | NULL | NULL | 6.0 | NULL | NULL (3 rows) 在 Analyze nation表之后: Analyze nation; ANALYZE: 6 rows --查询分析后的结果 SHOW STATS FOR nation; column_name | data_size | distinct_values_count | nulls_fraction | row_count | low_value | high_value -------------|-----------|-----------------------|----------------|-----------|-----------|------------ name | 45.0 | 5.0 | 0.0 | NULL | NULL | NULL regionkey | NULL | 2.0 | 0.0 | NULL | 0 | 2 NULL | NULL | NULL | NULL | 6.0 | NULL | NULL (3 rows)
  • 描述 使用CREATE TABLE创建一个具有指定列的、新的空表。使用CREATE TABLE AS创建带数据的表。 使用可选参数IF NOT EXISTS,如果表已经存在则不会报错。 WITH子句可用于在新创建的表或单列上设置属性,如表的存储位置(location)、是不是外表(external)等。 LIKE子句用于在新表中包含来自现有表的所有列定义。可以指定多个LIKE子句,从而允许从多个表中复制列。如果指定了INCLUDING PROPERTIES,则将所有表属性复制到新表中。如果WITH子句指定的属性名称与复制的属性名称相同,则将使用WITH子句中的值。默认是EXCLUDING PROPERTIES属性,而且最多只能为一个表指定INCLUDING PROPERTIES属性。 PARTITIONED BY能够用于指定分区的列;CLUSTERED BY能够被用于指定分桶的列;SORT BY和 SORTED BY能够用于给指定的分桶列进行排序;BUCKETS能够被用于指定分桶数;EXTERNAL可用于指定创建外部表;STORED AS能被用于指定文件存储的格式;LOCATION能被用于指定在HDFS上存储的路径。 想要查看支持哪些column属性,可以运行以下命令,会显示当前对接的catalog分别支持哪些列属性。 SELECT * FROM system.metadata.column_properties; 想要查看支持哪些table属性,可以运行以下命令: SELECT * FROM system.metadata.table_properties; 下表为catalog为hive时的查询结果。 SELECT * FROM system.metadata.table_properties where catalog_name = 'hive'; catalog_name property_name default_value type description hive auto_purge false boolean Skip trash when table or partition is deleted hive avro_schema_url - varchar URI pointing to Avro schema for the table hive bucket_count 0 integer Number of buckets hive bucketed_by [] array(varchar) Bucketing columns hive bucketing_version - integer Bucketing version hive csv_escape - varchar CSV escape character hive csv_quote - varchar CSV quote character hive csv_separator - varchar CSV separator character hive external_location - varchar File system location URI for external table hive format ORC varchar Hive storage format for the table. Possible values: [ORC, PARQUET, AVRO, RCBINARY, RCTEXT, SEQUENCEFILE, JSON, TEXTFILE, TEXTFILE_MULTIDELIM, CSV] hive orc_compress GZIP varchar Compression codec used. Possible values: [NONE, SNAPPY, LZ4, ZSTD, GZIP, ZLIB] hive orc_compress_size 262144 bigint orc compression size hive orc_row_index_stride 10000 integer no. of row index strides hive orc_stripe_size 67108864 bigint orc stripe size hive orc_bloom_filter_columns [] array(varchar) ORC Bloom filter index columns hive orc_bloom_filter_fpp 0.05 double ORC Bloom filter false positive probability hive partitioned_by [] array(varchar) Partition columns hive sorted_by [] array(varchar) Bucket sorting columns hive textfile_skip_footer_line_count - integer Number of footer lines hive textfile_skip_header_line_count - integer Number of header lines hive transactional false boolean Is transactional property enabled
  • 示例 创建一个新表orders,使用子句with指定创建表的存储格式、存储位置、以及是否为外表。 通过“auto.purge”参数可以指定涉及到数据移除操作(如DROP、DELETE、INSERT OVERWRITE、TRUNCATE TABLE)时是否清除相关数据: "auto.purge"='true'时,清除元数据和数据文件。 "auto.purge"='false'时,仅清除元数据,数据文件会移入HDFS回收站。默认值为“false”,且不建议用户修改此属性,避免数据删除后无法恢复。 CREATE TABLE orders ( orderkey bigint, orderstatus varchar, totalprice double, orderdate date ) WITH (format = 'ORC', location='/user',orc_compress='ZLIB',external=true, "auto.purge"=false); -- 通过DESC FORMATTED 语句,可以查看建表的详细信息 desc formatted orders ; Describe Formatted Table ------------------------------------------------------------------------------ # col_name data_type comment orderkey bigint orderstatus varchar totalprice double orderdate date # Detailed Table Information Database: default Owner: admintest LastAccessTime: 0 Location: hdfs://hacluster/user Table Type: EXTERNAL_TABLE # Table Parameters: EXTERNAL TRUE auto.purge false orc.compress.size 262144 orc.compression.codec ZLIB orc.row.index.stride 10000 orc.stripe.size 67108864 presto_query_id 20220812_084110_00050_srknk@default@HetuEngine presto_version 1.2.0-h0.cbu.mrs.320.r1-SNAPSHOT transient_lastDdlTime 1660293670 # Storage Information SerDe Library: org.apache.hadoop.hive.ql.io.orc.OrcSerde InputFormat: org.apache.hadoop.hive.ql.io.orc.OrcInputFormat OutputFormat: org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat Compressed: No Num Buckets: -1 Bucket Columns: [] Sort Columns: [] Storage Desc Params: serialization.format 1 (1 row) 创建一个新表,指定Row format: --建表时,指定表的字段分隔符为‘,’号(如果创建外表,要求数据文件中的每条记录的字段是以逗号进行分隔) CREATE TABLE student( id string,birthday string, grade int, memo string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ','; --建表时,指定字段分隔符为'\t',换行符为'\n' CREATE TABLE test( id int, name string , tel string) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' STORED AS TEXTFILE; 如果表orders不存在,则创建表orders,并且增加表注释和列注释: CREATE TABLE IF NOT EXISTS orders ( orderkey bigint, orderstatus varchar, totalprice double COMMENT 'Price in cents.', orderdate date ) COMMENT 'A table to keep track of orders.'; insert into orders values (202011181113,'online',9527,date '2020-11-11'), (202011181114,'online',666,date '2020-11-11'), (202011181115,'online',443,date '2020-11-11'), (202011181115,'offline',2896,date '2020-11-11'); 使用表orders的列定义创建表bigger_orders: CREATE TABLE bigger_orders ( another_orderkey bigint, LIKE orders, another_orderdate date ); SHOW CREATE TABLE bigger_orders ; Create Table --------------------------------------------------------------------- CREATE TABLE hive.default.bigger_orders ( another_orderkey bigint, orderkey bigint, orderstatus varchar, totalprice double, ordersdate date, another_orderdate date ) WITH ( external = false, format = 'ORC', location = 'hdfs://hacluster/user/hive/warehouse/bigger_orders', orc_compress = 'GZIP', orc_compress_size = 262144, orc_row_index_stride = 10000, orc_stripe_size = 67108864 ) (1 row) 标号① 建表示例: CREATE EXTERNAL TABLE hetu_test (orderkey bigint, orderstatus varchar, totalprice double, orderdate date) PARTITIONED BY(ds int) SORT BY (orderkey, orderstatus) COMMENT 'test' STORED AS ORC LOCATION '/user' TBLPROPERTIES (orc_compress = 'SNAPPY', orc_compress_size = 6710422, orc_bloom_filter_columns = 'orderstatus,totalprice'); 标号② 建表示例: CREATE EXTERNAL TABLE hetu_test1 (orderkey bigint, orderstatus varchar, totalprice double, orderdate date) COMMENT 'test' PARTITIONED BY(ds int) CLUSTERED BY (orderkey, orderstatus) SORTED BY (orderkey, orderstatus) INTO 16 BUCKETS STORED AS ORC LOCATION '/user' TBLPROPERTIES (orc_compress = 'SNAPPY', orc_compress_size = 6710422, orc_bloom_filter_columns = 'orderstatus,totalprice'); 标号③ 建表示例: CREATE TABLE hetu_test2 (orderkey bigint, orderstatus varchar, totalprice double, orderdate date, ds int) COMMENT 'This table is in Hetu syntax' WITH (partitioned_by = ARRAY['ds'], bucketed_by = ARRAY['orderkey', 'orderstatus'], sorted_by = ARRAY['orderkey', 'orderstatus'], bucket_count = 16, orc_compress = 'SNAPPY', orc_compress_size = 6710422, orc_bloom_filter_columns = ARRAY['orderstatus', 'totalprice'], external = true, format = 'orc', location = '/user');
  • 限制 session属性可以设置bucket_count,默认值为-1,表示未设置。创建分区表时,如果bucket_count为-1且建表语句中未设置buckets,则使用默认值16。 默认外部表存储位置/user/hive/warehouse/{schema_name}/{table_name},其中{schema_name}为建表时使用的schema,{table_name}为表名。 指定属性“transactional=true”可以让表支持“原子性、一致性、隔离性、持久性”写入的事务能力,但是将表定义为事务表后,无法通过设置“transactional=false”将其退化为非事务表。 transactional='true'或 '0'在执行过程中不会进行类型转换,所以这种写法会抛出异常: Cannot convert ['true'] to boolean Cannot convert ['0'] to boolean 默认不允许向托管表(表属性external = true)插入数据,如需使用该功能,可参考注意事项,添加hive自定义属性:hive.non-managed-table-writes-enabled=true。 Mppdb有一个限制,数据库的标识符的最大长度为63,如果把标识符命名超过了最大长度,那么会被自动截取掉超出的部分,只留下最大长度的标识符。 跨域场景不支持建表。
  • 语法 ① CREATE TABLE [ IF NOT EXISTS ] [catalog_name.][db_name.]table_name ( { column_name data_type [ NOT NULL ] [ COMMENT col_comment] [ WITH ( property_name = expression [, ...] ) ] | LIKE existing_table_name [ { INCLUDING | EXCLUDING } PROPERTIES ] } [, ...] ) [ COMMENT table_comment ] [ WITH ( property_name = expression [, ...] ) ] ② CREATE [EXTERNAL] TABLE [IF NOT EXISTS] [catalog_name.][db_name.]table_name ( { column_name data_type [ NOT NULL ] [ COMMENT comment ] [ WITH ( property_name = expression [, ...] ) ] | LIKE existing_table_name [ { INCLUDING | EXCLUDING } PROPERTIES ] } [, ...] ) [COMMENT 'table_comment'] [PARTITIONED BY(col_name data_type, ....)] [CLUSTERED BY (col_name, col_name, ...) [SORTED BY (col_name, col_name, ...)] INTO num_buckets BUCKETS] ] [ROW FORMAT row_format] [STORED AS file_format] [LOCATION 'hdfs_path'] [TBLPROPERTIES (orc_table_property = value [, ...] ) ] ③ CREATE [EXTERNAL] TABLE [IF NOT EXISTS] [catalog_name.][db_name.]table_name ( { column_name data_type [ NOT NULL ] [ COMMENT comment ] [ WITH ( property_name = expression [, ...] ) ] | LIKE existing_table_name [ { INCLUDING | EXCLUDING } PROPERTIES ] } [, ...] ) [PARTITIONED BY(col_name data_type, ....)] [SORT BY ([column [, column ...]])] [COMMENT 'table_comment'] [ROW FORMAT row_format] [STORED AS file_format] [LOCATION 'hdfs_path'] [TBLPROPERTIES (orc_table_property = value [, ...] ) ]
  • 示例 --查看show_table1的所有表属性 SHOW TBLPROPERTIES ----------------------------------------------------------------------------- STATS_GENERATED_VIA_STATS_TASK 'workaround for potential lack of HIVE-12730' auto.purge 'false' numFiles '0' numRows '0' orc.compress.size '262144' orc.compression.codec 'GZIP' orc.row.index.stride '10000' orc.stripe.size '67108864' presto_query_id '20230909_095107_00042_2hwbg@default@HetuEngine' presto_version '399' rawDataSize '0' totalSize '0' transient_lastDdlTime '1694253067' (1 row) --查看show_table1的压缩算法 SHOW TBLPROPERTIES show_table1('orc.compression.codec'); SHOW TBLPROPERTIES --------------------- GZIP (1 row)
  • 二进制函数 length(binary) → bigint 返回binary的字节长度。 select length(x'00141f');-- 3 concat(binary1, ..., binaryN) → varbinary 将binary1,binary2,binaryN串联起来。这个函数返回与SQL标准连接符||相同的功能。 select concat(X'32335F',x'00141f'); -- 32 33 5f 00 14 1f to_base64(binary) → varchar 将binary编码为base64字符串表示。 select to_base64(CAST('hello world' as binary)); -- aGVsbG8gd29ybGQ= from_base64(string) → varbinary 将base64编码的string解码为varbinary。 select from_base64('helloworld'); -- 85 e9 65 a3 0a 2b 95 unbase64(string) → varbinary 将base64编码的string解码为varbinary。 SELECT from_base64('helloworld'); -- 85 e9 65 a3 0a 2b 95 to_base64url(binary) → varchar 使用URL安全字符,将binary编码为base64字符串表示。 select to_base64url(x'555555'); -- VVVV from_base64url(string) → varbinary 使用URL安全字符,将base64编码的string解码为二进制数据。 select from_base64url('helloworld'); -- 85 e9 65 a3 0a 2b 95 to_hex(binary) → varchar 将binary编码为16进制字符串表示。 select to_hex(x'15245F'); -- 15245F from_hex(string) → varbinary 将16进制编码的string解码为二进制数据。 select from_hex('FFFF'); -- ff ff to_big_endian_64(bigint) → varbinary 将bigint类型的数字编码为64位大端补码格式。 select to_big_endian_64(1234); _col0 ------------------------- 00 00 00 00 00 00 04 d2 (1 row) from_big_endian_64(binary) → bigint 64位大端补码格式的二进制解码为bigint类型的数字。 select from_big_endian_64(x'00 00 00 00 00 00 04 d2'); _col0 ------- 1234 (1 row) to_big_endian_32(integer) → varbinary 将bigint类型的数字编码为32位大端补码格式。 select to_big_endian_32(1999); _col0 ------------- 00 00 07 cf (1 row) from_big_endian_32(binary) → integer 32位大端补码格式的二进制解码为bigint类型的数字。 select from_big_endian_32(x'00 00 07 cf'); _col0 ------- 1999 (1 row) to_ieee754_32(real) → varbinary 根据IEEE 754算法,将单精度浮点数编码为一个32位大端字节序的二进制块。 select to_ieee754_32(3.14); _col0 ------------- 40 48 f5 c3 (1 row) from_ieee754_32(binary) → real 对采用IEEE 754单精度浮点格式的32位大端字节序binary进行解码。 select from_ieee754_32(x'40 48 f5 c3'); _col0 ------- 3.14 (1 row) to_ieee754_64(double) → varbinary 根据IEEE 754算法,将双精度浮点数编码为一个64位大端字节序的二进制块。 select to_ieee754_64(3.14); _col0 ------------------------- 40 09 1e b8 51 eb 85 1f (1 row) from_ieee754_64(binary) → double 对采用IEEE 754单精度浮点格式的64位大端字节序binary进行解码。 select from_ieee754_64(X'40 09 1e b8 51 eb 85 1f'); _col0 ------- 3.14 (1 row) lpad(binary, size, padbinary) → varbinary 左填充二进制以使用padbinary调整字节大小。如果size小于二进制文件的长度,则结果将被截断为size个字符。size不能为负,并且padbinary不能为空。 select lpad(x'15245F', 11,x'15487F') ; -- 15 48 7f 15 48 7f 15 48 15 24 5f rpad(binary, size, padbinary) → varbinary 右填充二进制以使用padbinary调整字节大小。如果size小于二进制文件的长度,则结果将被截断为size个字符。size不能为负,并且padbinary不能为空。 SELECT rpad(x'15245F', 11,x'15487F'); -- 15 24 5f 15 48 7f 15 48 7f 15 48 crc32(binary) → bigint 计算二进制块的CRC 32值。 md5(binary) → varbinary 计算二进制块的MD 5哈希值。 sha1(binary) → varbinary 计算二进制块的SHA 1哈希值。 sha2(string, integer) → string 安全散列算法2, 是一种密码散列函数算法标准,其输出长度可以取224位,256位, 384位、512位,分别对应SHA-224、SHA-256、SHA-384、SHA512 sha256(binary) → varbinary 计算二进制块的SHA 256哈希值。 sha512(binary) → varbinary 计算二进制块的SHA 512哈希值。 xxhash64(binary) → varbinary 计算二进制块的XXHASH 64哈希值。 spooky_hash_v2_32(binary) → varbinary 计算二进制块的32位SpookyHashV2哈希值。 spooky_hash_v2_64(binary) → varbinary 计算二进制块的64位SpookyHashV2哈希值。 hmac_md5(binary, key) → varbinary 使用给定的key计算二进制块的HMAC值(采用 md5)。 hmac_sha1(binary, key) → varbinary 使用给定的key计算二进制块的HMAC值(采用 sha1)。 hmac_sha256(binary, key) → varbinary 使用给定的key计算二进制块的HMAC值(采用 sha256)。 hmac_sha512(binary, key) → varbinary 使用给定的key计算二进制块的HMAC值(采用 sha512)。 CRC32、MD5、SHA1算法在密码学场景已被攻击者破解,不建议应用于密码学安全场景。
  • 示例 SHOW functions; --使用LIKE子句 show functions like 'boo_%'; Function | Return Type | Argument Types | Function Type | Deterministic | Description ----------|-------------|----------------|---------------|---------------|------------- bool_and | boolean | boolean | aggregate | true | bool_or | boolean | boolean | aggregate | true | (2 rows) --如果匹配字符串中有字符与通配符冲突,可以指定转义字符来标识,示例为查询default这个schema下,table_name前缀为"t_" 的所有table,转义字符为"\": SHOW FUNCTIONS LIKE 'array\_%' escape '\'; Function | Return Type | Argument Types | Function Type | Deterministic | Description | Variable Arity | Built In -----------------|-------------|---------------------------------|---------------|--------------- |--------------------------------------------------------------------------------------------------------|----------------|---------- array_agg | array(T) | T | aggregate | true | return an array of values | false | true array_contains | boolean | array(T), T | scalar | true | Determines whether given value exists in the array | false | true array_distinct | array(E) | array(E) | scalar | true | Remove duplicate values from the given array | false | true array_except | array(E) | array(E), array(E) | scalar | true | Returns an array of elements that are in the first array but not the second, without duplicates. | false | true array_intersect | array(E) | array(E), array(E) | scalar | true | Intersects elements of the two given arrays | false | true array_join | varchar | array(T), varchar | scalar | true | Concatenates the elements of the given array using a delimiter and an optional string to replace nulls | false | true array_join | varchar | array(T), varchar, varchar | scalar | true | Concatenates the elements of the given array using a delimiter and an optional string to replace nulls | false | true array_max | T | array(T) | scalar | true | Get maximum value of array | false | true array_min | T | array(T) | scalar | true | Get minimum value of array | false | true array_position | bigint | array(T), T | scalar | true | Returns the position of the first occurrence of the given value in array (or 0 if not found) | false | true array_remove | array(E) | array(E), E | scalar | true | Remove specified values from the given array | false | true array_sort | array(E) | array(E) | scalar | true | Sorts the given array in ascending order according to the natural ordering of its elements. | false | true array_sort | array(T) | array(T), function(T,T,integer) | scalar | true | Sorts the given array with a lambda comparator. | false | true array_union | array(E) | array(E), array(E) | scalar | true | Union elements of the two given arrays | false | true --查看所有JAVA函数 SHOW external functions; Function | Owner ----------------------------|----------- example.namespace02.repeat | admintest hetu.default.add_two | admintest (2 rows) --查看给定函数的定义信息 SHOW external function example.namespace02.repeat; External Function -------------------------------------- External FUNCTION example.namespace02.repeat ( s varchar, n integer ) RETURNS varchar COMMENT 'repeat' LANGUAGE JAVA DETERMINISTIC CALLED ON NULL INPUT SYMBOL com.test.udf.hetuengine.functions.repeat URI hdfs://hacluster/user/hetuserver/udf/data/hetu_udf/udf-test-0.0.1-SNAPSHOT.jar FUNCPROPERTIES ( owner = 'admintest' )
  • 语法 [/*+ query_rewrite_hint*/] [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [ ALL | DISTINCT ] select_expression [, ...] [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] ] [ HAVING condition] [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ] [ ORDER BY expression [ ASC | DESC ] [, ...] ] [ OFFSET count [ ROW | ROWS ] ] [ LIMIT { count | ALL } ] [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES } ] from_item 可以是以下形式: table_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ] from_item join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ] table_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ] MATCH_RECOGNIZE pattern_recognition_specification [ [ AS ] alias [ ( column_alias [, ...] ) ] ] join_type 可以是以下形式: [ INNER ] JOIN LEFT [ OUTER ] JOIN RIGHT [ OUTER ] JOIN FULL [ OUTER ] JOIN LEFT [SEMI] JOIN RIGHT [SEMI] JOIN LEFT [ANTI] JOIN RIGHT [ANTI] JOIN CROSS JOIN grouping_element 可以是以下形式: () expression GROUPING SETS ( ( column [, ...] ) [, ...] ) CUBE ( column [, ...] ) ROLLUP ( column [, ...] )
  • FETCH FIRST FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES FETCH FIRST支持FIRST或NEXT关键字以及ROW或ROWS关键字。这些关键字等效,不影响query执行。 如果FETCH FIRST未指定数量,默认为1: SELECT orderdate FROM orders FETCH FIRST ROW ONLY; orderdate -------------- 2020-11-11 SELECT * FROM new_orders FETCH FIRST 2 ROW ONLY; orderkey | orderstatus | totalprice | orderdate --------------|-------------|------------|-------------- 202011181113 | online | 9527.0 | 2020-11-11 202011181114 | online | 666.0 | 2020-11-11 (2 rows) 如果使用了OFFSET,则LIMIT或FETCH FIRST会在OFFSET之后应用于结果集: SELECT * FROM (VALUES 5, 2, 4, 1, 3) t(x) ORDER BY x OFFSET 2 FETCH FIRST ROW ONLY; x --- 3 (1 row) 对于FETCH FIRST子句,参数ONLY或WITH TIES控制结果集中包含哪些行。 如果指定了ONLY参数,则结果集将限制为包含参数数量的前若干行。 如果指定了WITH TIES参数,则要求必须带ORDER BY子句。其结果集中包含符合条件的前若干行基本结果集以及额外的行。这些额外的返回行与基本结果集中最后一行的ORDER BY的参数一样: CREATE TABLE nation (name varchar, regionkey integer); insert into nation values ('ETHIOPIA',0),('MOROCCO',0),('ETHIOPIA',2),('KENYA',2),('ALGERIA',0),('MOZAMBIQUE',0); --返回regionkey与第一条相同的所有记录。 SELECT name, regionkey FROM nation ORDER BY regionkey FETCH FIRST ROW WITH TIES; name | regionkey ------------|----------- ALGERIA | 0 ETHIOPIA | 0 MOZAMBIQUE | 0 MOROCCO | 0 (4 rows)
  • 示例 下面这个例子,你可以看到每个阶段(Stage)的CPU时间消耗,每个计划节点相应的代价。 这个代价是基于现实时间(wall time),而非CPU 的相关时间。 对每一个计划节点,都可以看到额外的统计信息,例如每个节点实例的输入平均值,哈希碰撞(hash collisions)的平均次数。这些统计信息对于分析一条SQL语句中的数据异常情况(skewness数据倾斜,abnormal hash collisions)非常有用。 EXPLAIN ANALYZE SELECT count(*),sum(totalprice) FROM new_orders GROUP BY orderstatus; Query Plan ------------------------------------------------------------------------------------------------------------------------------- Fragment 1 [HASH] CPU: 29.19ms, Scheduled: 134.78ms, Input: 2 rows (77B); per task: avg.: 1.00 std.dev.: 1.00, Output: 2 rows (36B) Output layout: [count, sum] Output partitioning: SINGLE [] Stage Execution Strategy: UNGROUPED_EXECUTION Project[] │ Layout: [count:bigint, sum:double] │ Estimates: {rows: ? (?), cpu: ?, memory: ?, network: ?} │ CPU: 4.00ms (2.34%), Scheduled: 10.00ms (33.33%), Output: 2 rows (36B) │ Input avg.: 0.06 rows, Input std.dev.: 387.30% └─ Aggregate(FINAL)[orderstatus][$hashvalue] │ Layout: [orderstatus:varchar, $hashvalue:bigint, count:bigint, sum:double] │ Estimates: {rows: ? (?), cpu: ?, memory: ?, network: ?} │ CPU: 6.00ms (3.51%), Scheduled: 17.00ms (56.67%), Output: 2 rows (77B) │ Input avg.: 0.06 rows, Input std.dev.: 387.30% │ count := count("count_9") │ sum := sum("sum_10") └─ LocalExchange[HASH][$hashvalue] ("orderstatus") │ Layout: [orderstatus:varchar, sum_10:double, count_9:bigint, $hashvalue:bigint] │ Estimates: {rows: ? (?), cpu: ?, memory: ?, network: ?} │ CPU: 2.00ms (1.17%), Scheduled: 3.00ms (10.00%), Output: 2 rows (77B) │ Input avg.: 0.06 rows, Input std.dev.: 556.78% └─ RemoteSource[2] Layout: [orderstatus:varchar, sum_10:double, count_9:bigint, $hashvalue_11:bigint] CPU: 1.00ms (0.58%), Scheduled: 3.00ms (10.00%), Output: 2 rows (77B) Input avg.: 0.06 rows, Input std.dev.: 556.78% Fragment 2 [SOURCE] CPU: 17.35ms, Scheduled: 80.04ms, Input: 4 rows (81B); per task: avg.: 4.00 std.dev.: 0.00, Output: 2 rows (77B) Output layout: [orderstatus, sum_10, count_9, $hashvalue_12] Output partitioning: HASH [orderstatus][$hashvalue_12] Stage Execution Strategy: UNGROUPED_EXECUTION Aggregate(PARTIAL)[orderstatus][$hashvalue_12] │ Layout: [orderstatus:varchar, $hashvalue_12:bigint, sum_10:double, count_9:bigint] │ CPU: 1.00ms (0.58%), Scheduled: 6.00ms (20.00%), Output: 2 rows (77B) │ Input avg.: 4.00 rows, Input std.dev.: 0.00% │ sum_10 := sum("totalprice") │ count_9 := count(*) └─ ScanProject[table = hive:default:new_orders, grouped = false] Layout: [orderstatus:varchar, totalprice:double, $hashvalue_12:bigint] Estimates: {rows: 4 (292B), cpu: 256, memory: 0B, network: 0B}/{rows: 4 (292B), cpu: 548, memory: 0B, network: 0B} CPU: 16.00ms (9.36%), Scheduled: 132.00ms (440.00%), Output: 4 rows (117B) Input avg.: 4.00 rows, Input std.dev.: 0.00% $hashvalue_12 := "combine_hash"(bigint '0', COALESCE("$operator$hash_code"("orderstatus"), 0)) orderstatus := orderstatus:string:1:REGULAR totalprice := totalprice:double:2:REGULAR Input: 4 rows (81B), Filtered: 0.00% (1 row)
  • Flink客户端执行命令报错security.kerberos.login.keytab 客户端安装成功,执行客户端命令例如yarn-session.sh时报错,提示如下: [root@host01 bin]# yarn-session.sh 2018-10-25 01:22:06,454 | ERROR | [main] | Error while trying to split key and value in configuration file /opt/flinkclient/Flink/flink/conf/flink-conf.yaml:80: "security.kerberos.login.keytab: " | org.apache.flink.configuration.GlobalConfiguration (GlobalConfiguration.java:160) Exception in thread "main" org.apache.flink.configuration.IllegalConfigurationException: Error while parsing YAML configuration file :80: "security.kerberos.login.keytab: " 在安全集群环境下,Flink需要进行安全认证。当前客户端未进行相关安全认证设置。 Flink整个系统有两种认证方式: 使用kerberos认证:Flink yarn client、Yarn Resource Manager、JobManager、HDFS、TaskManager、Kafka和Zookeeper。 使用YARN内部的认证机制:Yarn Resource Manager与Application Master(简称AM)。 如果用户安装安全集群需要使用kerberos认证和security cookie认证。根据日志提示,发现配置文件中“security.kerberos.login.keytab :”配置项错误,未进行安全配置。 解决方法如下: 从MRS上下载用户的keytab认证文件,并放置到Flink客户端所在节点的某个目录下。 在“flink-conf.yaml”文件中配置: keytab路径。 security.kerberos.login.keytab: /home/flinkuser/keytab/abc222.keytab “/home/flinkuser/keytab/abc222.keytab”表示的是用户目录,为1中放置目录。 请确保客户端用户具备对应目录权限。 principal名。 security.kerberos.login.principal: abc222 对于HA模式,如果配置了ZooKeeper,还需要设置ZooKeeper Kerberos认证相关的配置。 zookeeper.sasl.disable: false security.kerberos.login.contexts: Client 如果用户对于Kafka Client和Kafka Broker之间也需要做Kerberos认证,配置如下: security.kerberos.login.contexts: Client,KafkaClient
  • 使用不同用户执行yarn-session创建Flink集群失败 使用Flink过程中,具有两个相同权限用户testuser和bdpuser。使用用户testuser创建Flink集群正常,但是切换至bdpuser用户创建Fllink集群时,执行yarn-session.sh命令报错: 2019-01-02 14:28:09,098 | ERROR | [main] | Ensure path threw exception | org.apache.flink.shaded.curator.org.apache.curator.framework.imps.CuratorFrameworkImpl (CuratorFrameworkImpl.java:566) org.apache.flink.shaded.zookeeper.org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /flink/application_1545397824912_0022 原因是高可用配置项未修改。由于在Flink的配置文件中,“high-availability.zookeeper.client.acl”默认为“creator”,仅创建者有权限访问,新用户无法访问ZooKeeper上的目录导致yarn-session.sh执行失败。 解决方法如下: 修改客户端配置文件“conf/flink-conf.yaml”中配置项“high-availability.zookeeper.path.root”,例如: high-availability.zookeeper.path.root: flink2 重新提交Flink任务。
  • CREATE/DROP/SHOW VIRTUAL SCHEMA(S) CREATE HetuEngine中的CREATE语句用来创建SCHEMA映射,通过映射信息对外开放本域数据源。 语法如下: CREATE VIRTUAL SCHEMA [ IF NOT EXISTS ] [ ctlg_dest.]schema_name WITH ( [catalog = ctlg_name,] schema = schm_name, [property_name = expression, ...] ) 创建一个virtual schema,需要在WITH中提供具体映射的schema信息。 ctlg_dest为在哪个数据源创建virtual schema,参数可选,如果不指定则取当前Session中的catalog,如果当前Session中也未指定catalog则会创建失败。 WITH必选,schema参数必选,catalog参数可选(如果不指定则取当前Session中的catalog)。 样例语句: CREATE VIRTUAL SCHEMA hive_default WITH (catalog = 'hive', schema = 'default'); DROP HetuEngine中的DROP语句用来删除SCHEMA映射。 语法如下: DROP VIRTUAL SCHEMA [ IF EXISTS ] schema_name schema_name也可以替换为全限定名(catalogName.virtualSchema)。 样例语句: DROP VIRTUAL SCHEMA hive_default; SHOW HetuEngine中的SHOW语句用来查询所有SCHEMA映射。 语法如下: SHOW VIRTUAL SCHEMAS [ FROM catalog ] [ LIKE pattern ] 样例语句: SHOW VIRTUAL SCHEMAS;
  • Ranking Functions cume_dist()→ bigint 描述:小于等于当前值的行数/分组内总行数–比如,统计小于等于当前薪水的人数,所占总人数的比例。 --查询示例 SELECT dept, userid, sal, CUME_DIST() OVER(ORDER BY sal) AS rn1, CUME_DIST() OVER(PARTITION BY dept ORDER BY sal) AS rn2 FROM salary; dept | userid | sal | rn1 | rn2 ------|--------|--------|-----|-------------------- d2 | user4 | 4000.0 | 0.8 | 0.5 d2 | user5 | 5000.0 | 1.0 | 1.0 d1 | user1 | 1000.0 | 0.2 | 0.3333333333333333 d1 | user2 | 2000.0 | 0.4 | 0.6666666666666666 d1 | user3 | 3000.0 | 0.6 | 1.0 (5 rows) dense_rank()→ bigint 描述:返回值在一组值中的排名。这与rank()相似,不同的是tie值不会在序列中产生间隙。 ntile(n)→ bigint 描述:用于将分组数据按照顺序切分成n片,返回当前切片值。NTILE不支持ROWS BETWEEN,比如NTILE(2) OVER(PARTITION BY cookieid ORDER BY createtime ROWS BETWEEN 3 PRECEDING AND CURRENT ROW)如果切片不均匀,默认增加第一个切片的分布。 --创建表并插入数据 create table cookies_log (cookieid varchar,createtime date,pv int); insert into cookies_log values ('cookie1',date '2020-07-10',1), ('cookie1',date '2020-07-11',5), ('cookie1',date '2020-07-12',7), ('cookie1',date '2020-07-13',3), ('cookie1',date '2020-07-14',2), ('cookie1',date '2020-07-15',4), ('cookie1',date '2020-07-16',4), ('cookie2',date '2020-07-10',2), ('cookie2',date '2020-07-11',3), ('cookie2',date '2020-07-12',5), ('cookie2',date '2020-07-13',6), ('cookie2',date '2020-07-14',3), ('cookie2',date '2020-07-15',9), ('cookie2',date '2020-07-16',7); -- 查询结果 SELECT cookieid,createtime,pv, NTILE(2) OVER(PARTITION BY cookieid ORDER BY createtime) AS rn1, --分组内将数据分成2片 NTILE(3) OVER(PARTITION BY cookieid ORDER BY createtime) AS rn2, --分组内将数据分成3片 NTILE(4) OVER(ORDER BY createtime) AS rn3 --将所有数据分成4片 FROM cookies_log ORDER BY cookieid,createtime; cookieid | createtime | pv | rn1 | rn2 | rn3 ----------|------------|----|-----|-----|----- cookie1 | 2020-07-10 | 1 | 1 | 1 | 1 cookie1 | 2020-07-11 | 5 | 1 | 1 | 1 cookie1 | 2020-07-12 | 7 | 1 | 1 | 2 cookie1 | 2020-07-13 | 3 | 1 | 2 | 2 cookie1 | 2020-07-14 | 2 | 2 | 2 | 3 cookie1 | 2020-07-15 | 4 | 2 | 3 | 4 cookie1 | 2020-07-16 | 4 | 2 | 3 | 4 cookie2 | 2020-07-10 | 2 | 1 | 1 | 1 cookie2 | 2020-07-11 | 3 | 1 | 1 | 1 cookie2 | 2020-07-12 | 5 | 1 | 1 | 2 cookie2 | 2020-07-13 | 6 | 1 | 2 | 2 cookie2 | 2020-07-14 | 3 | 2 | 2 | 3 cookie2 | 2020-07-15 | 9 | 2 | 3 | 3 cookie2 | 2020-07-16 | 7 | 2 | 3 | 4 (14 rows) percent_rank()→ double 描述:返回值在一组值中的百分比排名。 结果为(r-1)/(n-1),其中r是该行的rank(),n是窗口分区中的总行数。 SELECT dept,userid,sal, PERCENT_RANK() OVER(ORDER BY sal) AS rn1, --分组内 RANK() OVER(ORDER BY sal) AS rn11, --分组内RANK值 SUM(1) OVER(PARTITION BY NULL) AS rn12, --分组内总行数 PERCENT_RANK() OVER(PARTITION BY dept ORDER BY sal) AS rn2 from salary; dept | userid | sal | rn1 | rn11 | rn12 | rn2 ------|--------|--------|------|------|------|----- d2 | user4 | 4000.0 | 0.75 | 4 | 5 | 0.0 d2 | user5 | 5000.0 | 1.0 | 5 | 5 | 1.0 d1 | user1 | 1000.0 | 0.0 | 1 | 5 | 0.0 d1 | user2 | 2000.0 | 0.25 | 2 | 5 | 0.5 d1 | user3 | 3000.0 | 0.5 | 3 | 5 | 1.0 (5 rows) rank()→ bigint 描述:返回值在一组值中的排名。等级为1加上该行之前与该行不对等的行数。因此,排序中的平局值将在序列中产生缺口。对每个窗口分区执行排名。 SELECT cookieid, createtime, pv, RANK() OVER(PARTITION BY cookieid ORDER BY pv desc) AS rn1, DENSE_RANK() OVER(PARTITION BY cookieid ORDER BY pv desc) AS rn2, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY pv DESC) AS rn3 FROM cookies_log WHERE cookieid = 'cookie1'; cookieid | createtime | pv | rn1 | rn2 | rn3 ----------|------------|----|-----|-----|----- cookie1 | 2020-07-12 | 7 | 1 | 1 | 1 cookie1 | 2020-07-11 | 5 | 2 | 2 | 2 cookie1 | 2020-07-15 | 4 | 3 | 3 | 3 cookie1 | 2020-07-16 | 4 | 3 | 3 | 4 cookie1 | 2020-07-13 | 3 | 5 | 4 | 5 cookie1 | 2020-07-14 | 2 | 6 | 5 | 6 cookie1 | 2020-07-10 | 1 | 7 | 6 | 7 (7 rows) row_number()→ bigint 描述:从1开始,按照顺序,生成分组内记录的序列–比如,按照pv降序排列,生成分组内每天的pv名次ROW_NUMBER() 的应用场景非常多,再比如,获取分组内排序第一的记录。获取一个session中的第一条refer等。 SELECT cookieid, createtime, pv, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY pv desc) AS rn from cookies_log; cookieid | createtime | pv | rn ----------|------------- |----|---- cookie2 | 2020-07-15 | 9 | 1 cookie2 | 2020-07-16 | 7 | 2 cookie2 | 2020-07-13 | 6 | 3 cookie2 | 2020-07-12 | 5 | 4 cookie2 | 2020-07-14 | 3 | 5 cookie2 | 2020-07-11 | 3 | 6 cookie2 | 2020-07-10 | 2 | 7 cookie1 | 2020-07-12 | 7 | 1 cookie1 | 2020-07-11 | 5 | 2 cookie1 | 2020-07-15 | 4 | 3 cookie1 | 2020-07-16 | 4 | 4 cookie1 | 2020-07-13 | 3 | 5 cookie1 | 2020-07-14 | 2 | 6 cookie1 | 2020-07-10 | 1 | 7 (14 rows)
  • Value Functions 通常情况下,要重视null值。如果指定了IGNORE NULLS,那么计算中所有包含x为null值的行都会被排除掉,如果所有行的x字段值都是null值,将会返回默认值,否则返回null值。 -- 数据准备 create table cookie_views( cookieid varchar,createtime timestamp,url varchar); insert into cookie_views values ('cookie1',timestamp '2020-07-10 10:00:02','url20'), ('cookie1',timestamp '2020-07-10 10:00:00','url10'), ('cookie1',timestamp '2020-07-10 10:03:04','urll3'), ('cookie1',timestamp '2020-07-10 10:50:05','url60'), ('cookie1',timestamp '2020-07-10 11:00:00','url70'), ('cookie1',timestamp '2020-07-10 10:10:00','url40'), ('cookie1',timestamp '2020-07-10 10:50:01','url50'), ('cookie2',timestamp '2020-07-10 10:00:02','url23'), ('cookie2',timestamp '2020-07-10 10:00:00','url11'), ('cookie2',timestamp '2020-07-10 10:03:04','url33'), ('cookie2',timestamp '2020-07-10 10:50:05','url66'), ('cookie2',timestamp '2020-07-10 11:00:00','url77'), ('cookie2',timestamp '2020-07-10 10:10:00','url47'), ('cookie2',timestamp '2020-07-10 10:50:01','url55'); first_value(x)→ [same as input] 描述:返回窗口的第一个值。 SELECT cookieid, createtime, url, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY createtime) AS rn, FIRST_VALUE(url) OVER(PARTITION BY cookieid ORDER BY createtime) AS first1 FROM cookie_views; cookieid | createtime | url | rn | first1 ----------|-------------------------|-------|----|-------- cookie1 | 2020-07-10 10:00:00.000 | url10 | 1 | url10 cookie1 | 2020-07-10 10:00:02.000 | url20 | 2 | url10 cookie1 | 2020-07-10 10:03:04.000 | urll3 | 3 | url10 cookie1 | 2020-07-10 10:10:00.000 | url40 | 4 | url10 cookie1 | 2020-07-10 10:50:01.000 | url50 | 5 | url10 cookie1 | 2020-07-10 10:50:05.000 | url60 | 6 | url10 cookie1 | 2020-07-10 11:00:00.000 | url70 | 7 | url10 cookie2 | 2020-07-10 10:00:00.000 | url11 | 1 | url11 cookie2 | 2020-07-10 10:00:02.000 | url23 | 2 | url11 cookie2 | 2020-07-10 10:03:04.000 | url33 | 3 | url11 cookie2 | 2020-07-10 10:10:00.000 | url47 | 4 | url11 cookie2 | 2020-07-10 10:50:01.000 | url55 | 5 | url11 cookie2 | 2020-07-10 10:50:05.000 | url66 | 6 | url11 cookie2 | 2020-07-10 11:00:00.000 | url77 | 7 | url11 (14 rows) last_value(x)→ [same as input] 描述:返回窗口的最后一个值。 SELECT cookieid,createtime,url, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY createtime) AS rn, LAST_VALUE(url) OVER(PARTITION BY cookieid ORDER BY createtime) AS last1 FROM cookie_views; cookieid | createtime | url | rn | last1 ----------|-------------------------|-------|----|------- cookie2 | 2020-07-10 10:00:00.000 | url11 | 1 | url11 cookie2 | 2020-07-10 10:00:02.000 | url23 | 2 | url23 cookie2 | 2020-07-10 10:03:04.000 | url33 | 3 | url33 cookie2 | 2020-07-10 10:10:00.000 | url47 | 4 | url47 cookie2 | 2020-07-10 10:50:01.000 | url55 | 5 | url55 cookie2 | 2020-07-10 10:50:05.000 | url66 | 6 | url66 cookie2 | 2020-07-10 11:00:00.000 | url77 | 7 | url77 cookie1 | 2020-07-10 10:00:00.000 | url10 | 1 | url10 cookie1 | 2020-07-10 10:00:02.000 | url20 | 2 | url20 cookie1 | 2020-07-10 10:03:04.000 | urll3 | 3 | urll3 cookie1 | 2020-07-10 10:10:00.000 | url40 | 4 | url40 cookie1 | 2020-07-10 10:50:01.000 | url50 | 5 | url50 cookie1 | 2020-07-10 10:50:05.000 | url60 | 6 | url60 cookie1 | 2020-07-10 11:00:00.000 | url70 | 7 | url70 (14 rows) nth_value(x, offset)→ [same as input] 描述:返回距窗口开头指定偏移量的值。偏移量从1开始。偏移量可以是任何标量表达式。如果偏移量为null或大于窗口中的值数,则返回null。偏移量不允许为0或者负数。 SELECT cookieid,createtime,url, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY createtime) AS rn, NTH_VALUE(url,3) OVER(PARTITION BY cookieid ORDER BY createtime) AS last1 FROM cookie_views; cookieid | createtime | url | rn | last1 ----------|-------------------------|-------|----|------- cookie1 | 2020-07-10 10:00:00.000 | url10 | 1 | NULL cookie1 | 2020-07-10 10:00:02.000 | url20 | 2 | NULL cookie1 | 2020-07-10 10:03:04.000 | urll3 | 3 | urll3 cookie1 | 2020-07-10 10:10:00.000 | url40 | 4 | urll3 cookie1 | 2020-07-10 10:50:01.000 | url50 | 5 | urll3 cookie1 | 2020-07-10 10:50:05.000 | url60 | 6 | urll3 cookie1 | 2020-07-10 11:00:00.000 | url70 | 7 | urll3 cookie2 | 2020-07-10 10:00:00.000 | url11 | 1 | NULL cookie2 | 2020-07-10 10:00:02.000 | url23 | 2 | NULL cookie2 | 2020-07-10 10:03:04.000 | url33 | 3 | url33 cookie2 | 2020-07-10 10:10:00.000 | url47 | 4 | url33 cookie2 | 2020-07-10 10:50:01.000 | url55 | 5 | url33 cookie2 | 2020-07-10 10:50:05.000 | url66 | 6 | url33 cookie2 | 2020-07-10 11:00:00.000 | url77 | 7 | url33 (14 rows) lead(x[, offset[, default_value]])→ [same as input] 描述:返回窗口分区中当前行之后的偏移行处的值。偏移量从0开始,即当前行。偏移量可以是任何标量表达式。默认偏移量为1。如果偏移量为null,则返回null。如果偏移量指向不在分区内的行,则返回default_value,或者如果未指定,则返回null。lead()函数要求指定窗口顺序。不得指定窗框。 SELECT cookieid,createtime,url, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY createtime) AS rn, LEAD(createtime,1,timestamp '2020-01-01 00:00:00') OVER(PARTITION BY cookieid ORDER BY createtime) AS next_1_time, LEAD(createtime,2) OVER(PARTITION BY cookieid ORDER BY createtime) AS next_2_time FROM cookie_views; cookieid | createtime | url | rn | next_1_time | next_2_time ----------|-------------------------|-------|----|-------------------------|------------------------- cookie2 | 2020-07-10 10:00:00.000 | url11 | 1 | 2020-07-10 10:00:02.000 | 2020-07-10 10:03:04.000 cookie2 | 2020-07-10 10:00:02.000 | url23 | 2 | 2020-07-10 10:03:04.000 | 2020-07-10 10:10:00.000 cookie2 | 2020-07-10 10:03:04.000 | url33 | 3 | 2020-07-10 10:10:00.000 | 2020-07-10 10:50:01.000 cookie2 | 2020-07-10 10:10:00.000 | url47 | 4 | 2020-07-10 10:50:01.000 | 2020-07-10 10:50:05.000 cookie2 | 2020-07-10 10:50:01.000 | url55 | 5 | 2020-07-10 10:50:05.000 | 2020-07-10 11:00:00.000 cookie2 | 2020-07-10 10:50:05.000 | url66 | 6 | 2020-07-10 11:00:00.000 | NULL cookie2 | 2020-07-10 11:00:00.000 | url77 | 7 | 2020-01-01 00:00:00.000 | NULL cookie1 | 2020-07-10 10:00:00.000 | url10 | 1 | 2020-07-10 10:00:02.000 | 2020-07-10 10:03:04.000 cookie1 | 2020-07-10 10:00:02.000 | url20 | 2 | 2020-07-10 10:03:04.000 | 2020-07-10 10:10:00.000 cookie1 | 2020-07-10 10:03:04.000 | urll3 | 3 | 2020-07-10 10:10:00.000 | 2020-07-10 10:50:01.000 cookie1 | 2020-07-10 10:10:00.000 | url40 | 4 | 2020-07-10 10:50:01.000 | 2020-07-10 10:50:05.000 cookie1 | 2020-07-10 10:50:01.000 | url50 | 5 | 2020-07-10 10:50:05.000 | 2020-07-10 11:00:00.000 cookie1 | 2020-07-10 10:50:05.000 | url60 | 6 | 2020-07-10 11:00:00.000 | NULL cookie1 | 2020-07-10 11:00:00.000 | url70 | 7 | 2020-01-01 00:00:00.000 | NULL (14 rows) lag(x[, offset[, default_value]])→ [same as input] 描述:返回窗口分区中当前行之前的偏移行的值,偏移量从0开始,即当前行,偏移量可以是任何标量表达式,默认偏移量为1。如果偏移量为null,则返回null。如果偏移量指向不在分区内的行,则返回default_value。如果未指定,则返回null。lag()函数要求指定窗口顺序,不得指定窗框。 SELECT cookieid, createtime, url, ROW_NUMBER() OVER(PARTITION BY cookieid ORDER BY createtime) AS rn, LAG(createtime,1, timestamp '2020-01-01 00:00:00') OVER(PARTITION BY cookieid ORDER BY createtime) AS last_1_time, LAG(createtime,2) OVER(PARTITION BY cookieid ORDER BY createtime) AS last_2_time FROM cookie_views; cookieid | createtime | url | rn | last_1_time | last_2_time ----------|-------------------------|-------|----|-------------------------|----------------------- cookie2 | 2020-07-10 10:00:00.000 | url11 | 1 | 2020-01-01 00:00:00.000 | NULL cookie2 | 2020-07-10 10:00:02.000 | url23 | 2 | 2020-07-10 10:00:00.000 | NULL cookie2 | 2020-07-10 10:03:04.000 | url33 | 3 | 2020-07-10 10:00:02.000 | 2020-07-10 10:00:00.000 cookie2 | 2020-07-10 10:10:00.000 | url47 | 4 | 2020-07-10 10:03:04.000 | 2020-07-10 10:00:02.000 cookie2 | 2020-07-10 10:50:01.000 | url55 | 5 | 2020-07-10 10:10:00.000 | 2020-07-10 10:03:04.000 cookie2 | 2020-07-10 10:50:05.000 | url66 | 6 | 2020-07-10 10:50:01.000 | 2020-07-10 10:10:00.000 cookie2 | 2020-07-10 11:00:00.000 | url77 | 7 | 2020-07-10 10:50:05.000 | 2020-07-10 10:50:01.000 cookie1 | 2020-07-10 10:00:00.000 | url10 | 1 | 2020-01-01 00:00:00.000 | NULL cookie1 | 2020-07-10 10:00:02.000 | url20 | 2 | 2020-07-10 10:00:00.000 | NULL cookie1 | 2020-07-10 10:03:04.000 | urll3 | 3 | 2020-07-10 10:00:02.000 | 2020-07-10 10:00:00.000 cookie1 | 2020-07-10 10:10:00.000 | url40 | 4 | 2020-07-10 10:03:04.000 | 2020-07-10 10:00:02.000 cookie1 | 2020-07-10 10:50:01.000 | url50 | 5 | 2020-07-10 10:10:00.000 | 2020-07-10 10:03:04.000 cookie1 | 2020-07-10 10:50:05.000 | url60 | 6 | 2020-07-10 10:50:01.000 | 2020-07-10 10:10:00.000 cookie1 | 2020-07-10 11:00:00.000 | url70 | 7 | 2020-07-10 10:50:05.000 | 2020-07-10 10:50:01.000 (14 rows)
  • Aggregate Functions 所有的聚合函数都能通过添加over子句来当做窗口函数使用。聚合函数将在当前窗口框架下的每行记录进行运算。 下面的查询生成每个职员按天计算的订单价格的滚动总和。 select dept,userid,sal,sum(sal) over (partition by dept order by sal desc) as rolling_sum from salary order by dept,userid,sal; dept | userid | sal | rolling_sum ------|--------|--------|------------- d1 | user1 | 1000.0 | 6000.0 d1 | user2 | 2000.0 | 5000.0 d1 | user3 | 3000.0 | 3000.0 d2 | user4 | 4000.0 | 9000.0 d2 | user5 | 5000.0 | 5000.0 (5 rows)
  • TRY 评估一个表达式,如果出错,则返回Null。类似于编程语言中的try catch。try函数一般结合COALESCE使用,COALESCE可以将异常的空值转为0或者空,以下情况会被try捕获: 分母为0 错误的cast操作或者函数入参 数字超过了定义长度 不推荐使用,应该明确以上异常,做数据预处理 示例: 假设有以下表,字段origin_zip中包含了一些无效数据: -- 创建表 create table shipping (origin_state varchar,origin_zip varchar,packages int ,total_cost int); -- 插入数据 insert into shipping values ('California','94131',25,100), ('California','P332a',5,72), ('California','94025',0,155), ('New Jersey','08544',225,490); -- 查询数据 SELECT * FROM shipping; origin_state | origin_zip | packages | total_cost --------------+------------+----------+------------ California | 94131 | 25 | 100 California | P332a | 5 | 72 California | 94025 | 0 | 155 New Jersey | 08544 | 225 | 490 (4 rows) 不使用Try查询失败: SELECT CAST(origin_zip AS BIGINT) FROM shipping; Query failed: Cannot cast 'P332a' to BIGINT 使用Try返回NULL: SELECT TRY(CAST(origin_zip AS BIGINT)) FROM shipping; origin_zip ------------ 94131 NULL 94025 08544 (4 rows) 不使用try查询失败: SELECT total_cost/packages AS per_package FROM shipping; Query failed: Division by zero 使用TRY和COALESCE返回默认值: SELECT COALESCE(TRY(total_cost/packages),0) AS per_package FROM shipping; per_package ------------- 4 14 0 19 (4 rows)
  • NULLIF nullif(value1, value2) 如果value1与value2相等,返回NULL;否则返回value1 。 select nullif(a,b) from (values (1,1),(1,2)) as t(a,b); -- _col0 ------- NULL 1 (2 rows) ZEROIFNULL(value) 如果value为null,返回0,否则返回原值。目前支持数值类型还有varchar类型。 select zeroifnull(a),zeroifnull(b),zeroifnull(c) from (values (null,13.11,bigint '157'),(88,null,bigint '188'),(55,14.11,null)) as t(a,b,c); _col0 | _col1 | _col2 -------|-------|------- 0 | 13.11 | 157 88 | 0.00 | 188 55 | 14.11 | 0 (3 rows) NVL(value1,value2) 如果value1为NULL,返回value2,否则,返回value1。 select nvl(NULL,3); -- 3 select nvl(2,3); --2 ISNULL(value) 如果value1为NULL,返回true,否则返回false。 Create table nulltest(col1 int,col2 int); insert into nulltest values(null,3); select isnull(col1),isnull(col2) from nulltest; _col0 | _col1 -------|------- true | false (1 row) ISNOTNULL(value) 如果value1为NULL,返回false,否则返回true。 select isnotnull(col1),isnotnull(col2) from nulltest; _col0 | _col1 -------|------- false | true (1 row)
  • IF IF函数是语言结构,它与下面的CASE表达式功能相同: CASE WHEN condition THEN true_value [ ELSE false_value ] END if(condition, true_value) 如果condition为真,返回true_value;否则返回NULL,true_value不进行计算。 select if(a=1,8) from (values (1),(1),(2)) as t(a); -- 8 8 NULL select if(a=1,'value') from (values (1),(1),(2)) as t(a); -- value value NULL if(condition, true_value, false_value) 如果condition为真,返回true_value;否则计算并返回false_value 。 select if(a=1,'on','off') from (values (1),(1),(2)) as t(a); _col0 ------- on on off (3 rows)
  • CASE 标准的SQL CASE表达式有两种模式。 “简单模式”从左向右查找表达式的每个value,直到找出相等的expression: CASE expression WHEN value THEN result [ WHEN ... ] [ ELSE result ] END 返回匹配value的result。如果没有匹配到任何值,则返回ELSE子句的result;如果没有ELSE子句,则返回空。示例: select a, case a when 1 then 'one' when 2 then 'two' else 'many' end from (values (1),(2),(3),(4)) as t(a); a | _col1 ---|------- 1 | one 2 | two 3 | many 4 | many (4 rows) “查找模式”从左向右判断每个condition的布尔值,直到判断为真,返回匹配result: CASE WHEN condition THEN result [ WHEN ... ] [ ELSE result ] END 如果判断条件都不成立,则返回ELSE子句的result;如果没有ELSE子句,则返回空。示例: select a,b, case when a=1 then 'one' when b=2 then 'tow' else 'many' end from (values (1,2),(3,4),(1,3),(4,2)) as t(a,b); a | b | _col2 ---|---|------- 1 | 2 | one 3 | 4 | many 1 | 3 | one 4 | 2 | tow (4 rows)
  • HetuEngine常用数据源语法兼容性说明 语法 Hive MPPDB Elasticsearch HBase HetuEngine(跨域) ClickHouse Hudi MySQL 数据库的show schemas Y Y Y Y Y Y Y Y 数据库的create schema Y Y N Y N N Y N 数据库的use schema Y Y Y Y Y Y Y Y 数据库的alter schema Y N N N N N N N 数据库的drop schema Y Y Y Y N N Y N 表的show tables/show create table/show functions/show session Y Y Y Y Y Y Y Y 表的create Y Y N Y N N N N 表的create table TABLENAME as Y Y Y Y N N N N 表的insert into TABLENAME values Y Y Y Y Y N N N 表的insert into TABLENAME select Y Y Y Y Y N N N 表的insert overwrite TABLENAME values Y N N N N N N N 表的insert overwrite TABLENAME select Y N N N N N N N 表的alter Y Y N N N N N N 表的select Y Y Y Y Y Y Y Y 表的update Y Y Y N N N N N 表的delete Y Y Y Y N N N N 表的drop Y N Y Y Y N N N 表的desc/describe TABLENAME Y Y Y Y Y Y Y Y 表的analyze Y Y Y N N N Y N 表的comment Y N N N N N N N 表的explain Y Y Y Y Y N Y N 表的show stats Y Y Y N N N Y N 表的show columns Y Y Y Y Y Y Y Y 表的select column Y Y Y Y Y Y Y Y 视图的create view Y Y N N N N N N 视图的create or replace view Y N N N N N N N 视图的alter Y N N N N N N N 视图的drop Y N N N N N N N 视图的select Y Y N N Y Y Y Y 视图的desc/describe VIEWNAME Y Y N N Y Y Y Y 视图的show views/show create view Y Y N N N Y Y Y 视图的show columns Y Y Y Y Y Y Y Y 视图的select column Y Y Y Y Y Y Y Y 父主题: HetuEngine常见SQL语法说明
  • 示例 列出当前catalog所有的schemas: SHOW SCHEMAS; 列出指定catalog下的schema_name前缀为"t"的所有schemas: SHOW SCHEMAS FROM hive LIKE 't%'; --等价写法: SHOW SCHEMAS IN hive LIKE 't%'; 如果匹配字符串中有字符与通配符冲突,可以指定转义字符来标识,示例为查询hive这个catalog下,schema_name前缀为“pm_”的所有schema,转义字符为“/”: SHOW SCHEMAS IN hive LIKE 'pm/_%' ESCAPE '/';
  • SHOW语法使用概要 SHOW语法主要用来查看数据库对象的相关信息,其中LIKE子句用来对数据库对象过滤,匹配规则如下,具体示例可参看SHOW TABLES: 规则1:_可以用来匹配单个任意字符。 规则2:%可以用来匹配0个或者任意个任意字符。 规则3:* 可以用来匹配0个或者任意个任意字符。 规则4:|可以用来配置多种规则,规则之间用“|”分隔。 规则5:当想将“_”作为匹配条件时,可以使用ESCAPE 指定一个转义字符,对“_”进行转义,以免按照规则1对“_”进行解析。 父主题: HetuEngine DDL SQL语法说明
  • 示例 收集表fruit的统计信息: ANALYZE fruit; 统计catalog hive、schema default下的表存储: ANALYZE hive.default.orders; 从hive分区表中统计分区'2020-07-17' , '2020-07-18'信息: ANALYZE hive.web.page_views WITH (partitions = ARRAY[ARRAY['2020-07-17','US'], ARRAY['2020-07-18','US']]);
共100000条