Hive知识点总结

Hive支持的数据类型

primitive_type
array_type
map_type
struct_type 

DDL

create table t1(
    id int,
    name string,
) row format delimited
  fields terminated by '\t'                 // 字段之间用'\t'隔开
  lines terminated by '\n'                  // 行元素之间用'\n'隔开
  collection terminated by ','              // 数组元素之间用','隔开
  map keys terminated by ':';               // Map元素之间用','隔开

加载数据的两种方式

load data local inpath '/user/local/test.txt' into table t1;   // 从本地文件加载数据
load data inpath '/user/local/test.txt' into table t1;         // 从hdfs文件加载数据
insert into table t1 select id, name from t2;                  // 从其他表中加载数据

分区

// 创建分区表
create table t1(
    id int,
    name string,
) PARTITIONED BY (dt string);

// 加载数据
load data local inpath '/user/local/test1.txt' into t1 partition (date = '2018-3-28')
load data local inpath '/user/local/test2.txt' into t1 partition (date = '2018-3-29')

// 查询数据
select * from t1 where date = "2018-03-28"

Regex

数据:
192.168.57.4 - - [29/Feb/2016:18:14:35 +0800] "GET /bg-upper.png HTTP/1.1" 304

create table log(
    host string,
    identity string,
    t_user string,
    time string,
    request string,
    referer string,
    agent string
)
row format serde 'org.apache.hadoop.hive.serde2.RegexSerDe'
with serdeproperties(
    ""input.regex" = "([^ ]*) ([^ ]*) ([^ ]*) \\[(.*)\\] \"(.*)\" (-|[0-9]*) (-|[0-9]*)" "
)
stored as textfile

load data local inpath '/user/local/log.txt' into table log;

自定义函数

UDF:一个输入,一个输出,比如year,date_sub
UDAF:多个输入,一个输出,比如countsumavg
UDTF:操作行列,比如explode

Hive分桶(哈希桶)

create table t_bucket(
    id int
) clustered by (id) into 3 buckets;

load方法加载数据时不会进行分桶,只有从其他表加载数据时才会进行分桶

Hive运行方式

hive -S -f hive-test.hql > result.csv               // 覆盖
hive -S -e "select id from t1" >> result.csv        // 追加

Hive的wordcount

select w.word, count(w.word) as count from
    (select explode(split(line, " ")) as word from t_word) w
        group by w.word order by count desc;

Hive优化

1.本地模式提高执行效率:set hive.exec.mode.local.auto = true

2.并行计算:
    select wc.col, bk.col2 from(
        (select count(*) as col1 from table_1) wc,
        (select count(*) as col2 from table_2) bk);
    set hive.exec.mode.local.auto = true

3.严格模式:
    查询限制:1)对于分区表,必须添加where条件
            2order by 语句必须包含limit限制
            3)限制执行笛卡儿积的查询
    set hive.mapred.mode = strict
4.Hive排序:
    Order By:对于查询结果做全排序,只允许有一个 reduce 处理。当数据量较大时,应慎用。严格 模式下,必须结合 limit 来使用
    Sort By:对于单个 reduce 的数据进行排序
    Distribute By:分区排序,经常和 Sort By 结合使用
    Cluster By:相当于 Sort By + Distribute By,Cluster By 不能通过 ascdesc 的方式指定排序规则; 可通过 distribute by column sort by column asc|desc 的方式结合使用

5.Hive JoinJoin计算时,将小表放在左边(驱动表)
    Map Join:在Map端完成Join(避免数据倾斜):
    SQL 方式,在 SQL 语句中添加 MapJoin 标记(mapjoin hint) 语法
    set hive.auto.convert.join = true

6.Map-Side聚合
    set hive.map.aggr = true

7.控制 Hive 中 Map 以及 Reduce 的数量 

8.JVM重用

你可能感兴趣的:(Study)