1. 程式人生 > >hive基礎1

hive基礎1

事務表 封裝 學習 res 原始的 水平 修改配置 url from

Hive基礎

1、介紹

Hive是OLAP(online analyze process,在線分析處理)。通常稱為數據倉庫,簡稱數倉。內置很多分析函數,可進行海量數據的在線分析處理。hive構建在hadoop之上,使用hdfs作為進行存儲,計算過程采用的是Mapreduce完成,本質上hive是對hadoop的mr的封裝,通過原始的mr方式進行數據處理與分析,往往效率較低,而且具有相當的復雜度,學習曲線較長。hive常用傳統的sql方式作為操作手段,極大的降低了學習曲線,畢竟大部分人對sql還是比較熟悉的。但在運行時,仍然要將sql進行翻譯成mapreduce程序進行。

2、hive安裝

下載hive的軟件包,解壓之後配置環境變量即可。

3、hive配置

hive中元數據存在關系型數據庫中,默認是derby數據庫,這裏改成mysql數據庫。hive的配置文件為conf/hive-site.xml目錄下:

<configuration>
  ...
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>com.mysql.jdbc.Driver</value>
    <description>Driver class name for a JDBC metastore</description>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:mysql://192.168.231.1:3306/big11_hive</value>
    <description>
      JDBC connect string for a JDBC metastore.
      To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
      For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
    </description>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionUserName</name>
    <value>root</value>
    <description>Username to use against metastore database</description>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionPassword</name>
    <value>root</value>
    <description>password to use against metastore database</description>
  </property>
  <property>
    <name>hive.server2.enable.doAs</name>
    <value>false</value>
    <description>
      Setting this property to true will have HiveServer2 execute
      Hive operations as the user making the calls to it.
    </description>
  </property>
  <property>
    <name>hive.metastore.schema.verification</name>
    <value>false</value>
    <description>
      Enforce metastore schema version consistency.
      True: Verify that version information stored in metastore matches with one from Hive jars.  Also disable automatic
            schema migration attempt. Users are required to manually migrate schema after Hive upgrade which ensures
            proper metastore schema migration. (Default)
      False: Warn if the version information stored in metastore doesn‘t match with one from in Hive jars.
    </description>
  </property>


  ...
</configuration>

通過hive命令查看或者修改配置:

  1. header設置

    # 查看屬性
    $hive>set hive.cli.print.header ;
    # 修改屬性
    $hive>set hive.cli.print.header=true ;

    ?

4、初始化數據庫

$>schematool -dbtype mysql -dbType mysql -initSchema

5、登錄hive的命令行終端

$>hive
$hive>

6、hive常用命令

  1. 創建數據庫

    $hive>create database if not exists big12 ;

    ?

  2. 刪除庫

    $hive>drop database if exists big12 ;

    ?

  3. 創建表

    $hive>CREATE TABLE if not exists emp(
    id int ,
    name string ,
    age int,
    dep string,
    salary int
    )
    ROW FORMAT DELIMITED
    FIELDS TERMINATED BY ‘,‘
    lines terminated by  ‘\n‘
    stored as textfile;
    
  4. 準備數據上傳到emp表

    [emp.txt]

    1,tom,22,001,3000
    2,tomas,22,001,2500
    3,tomasLee,25,002,1200
    4,tomson,24,002,3400
    5,peter,24,001,3800
    6,john,25,001,4200
    7,looser,24,001,5500
    8,alex,25,003,6000
    9,jason,24,003,6000
    10,japser,22,003,3000
    # local是上傳文件到hdfs上(hive倉庫目錄下)
    $hive>load data local inpath ‘/home/centos/emp2.txt‘ into table emp ;
    
    # 移動hdfs的目錄到hive的表目錄下。
    $hive>load data inpath ‘/user/centos/emp.txt‘ into table emp ;
    
  5. 重命名表

    $hive>alter table emp rename to e ;

7、hive的復雜類型

7.1類型

  1. map

    映射,key-value對

  2. struct

    結構體,相當於元組(等價於java的實體類),有多個屬性,每個屬性有不同類型。在RDBMS中相當於一行記錄。

  3. array

    也可以成為list,有多行構成。

7.2 使用復雜類型

  1. 創建表

    $hive>CREATE TABLE emp(
    name string,
    arr ARRAY<string>,
    stru STRUCT<sex:string,age:int>,
    map1 MAP<string,int>,
    map2 MAP<string,ARRAY<string>>
    )
    ROW FORMAT DELIMITED
    FIELDS TERMINATED BY ‘|‘
    COLLECTION ITEMS TERMINATED BY ‘,‘
    MAP KEYS TERMINATED BY ‘:‘
    lines terminated by ‘\n‘;
  2. 準備數據

    Michael|Montreal,Toronto|Male,30|DB:80|Product:Developer^DLead
    Will|Montreal|Male,35|Perl:85|Product:Lead,Test:Lead
    Shelley|New York|Female,27|Python:80|Test:Lead,COE:Architect
    Lucy|Vancouver|Female,57|Sales:89,HR:94|Sales:Lead
  3. 查詢復雜數據類型

    $hive>select arr[0] , stru.sex , map1["DB"] ,map2["Product"][0] from emp ;
  4. CTAS方式創建表

    # create table as .. select ..
    $hive>create table emp2 ROW FORMAT DELIMITED
    FIELDS TERMINATED BY ‘|‘
    COLLECTION ITEMS TERMINATED BY ‘,‘
    MAP KEYS TERMINATED BY ‘:‘
    lines terminated by ‘\n‘ as select name ,arr from emp ;
  5. Like方式創建表

    like方式創建表和原表結構相同,不攜帶數據。

    $hive>create external table emp3 like emp ;
  6. 表數據復制

    $hive>insert into emp3 select * from emp ;

8、復雜類型對應的函數

  1. 查看所有函數

    $hive>show functions ;

    ?

  2. 查看函數幫助

    # 查看函數
    $hive>desc function array ;
    
    # 查看函數擴展信息
    $hive>desc function extended array ;
  3. array()

    $hive>select array(1,2,3) ;
  4. struct()

    不帶名成的結構體。

    # 構造結構體
    $hive>select struct(1, ‘tomas‘ , 12 ,‘hebei‘ , 80000) ;
    # 無名列,使用coln訪問
    $hive>select struct(1, ‘tomas‘ , 12 ,‘hebei‘ , 80000).col5 ;

    ?

  5. named_struct()

    帶有名稱的結構體。

    # 構造帶名結構體
    $hive>select named_struct(‘id‘,1,‘name‘,‘tomas‘,‘sal‘ , 80000) ;
    # 查詢特定字段
    $hive>select named_struct(‘id‘,1,‘name‘,‘tomas‘,‘sal‘ , 80000).sal ;
  6. map()

    map()函數試音key-value映射,使用方式同named_struct相類似。

    # 構造帶名結構體
    $hive>select map(‘id‘,1,‘name‘,‘tomas‘,‘sal‘ , 80000) ;
    # 查詢特定字段
    $hive>select map(‘id‘,1,‘name‘,‘tomas‘,‘sal‘ , 80000).sal ;

    ?

    ?

9、分區表

在表目錄再根據分區字段創建的子目錄,能夠有效縮小搜索範圍。

  1. 創建分區表

    $hive>CREATE TABLE par1(
    id int,
    name string,
    age int
    )
    PARTITIONED BY (prov string, city string)
    ROW FORMAT DELIMITED
    FIELDS TERMINATED BY ‘|‘
    COLLECTION ITEMS TERMINATED BY ‘,‘
    MAP KEYS TERMINATED BY ‘:‘
    lines terminated by ‘\n‘;

    ?

  2. 手動添加分區

    $hive>alter table par1 add partition(prov=‘henan‘ , city=‘kaifeng‘) partition(prov=‘henan‘ , city=‘zhengzhou‘); 
  3. 顯式分區信息

    $hive>show partitions par1 ;
  4. 刪除分區

    $hive>alter table par1 DROP IF EXISTS PARTITION (prov=‘henan‘ , city=‘kaifeng‘);
  5. 加載數據到分區

    $hive>load data local inpath ‘/home/centos/1.txt‘ into table par1 partition(prov=‘henan‘ , city=‘kaifeng‘) ;
    # -f :force 覆蓋原有文件
    $>hdfs dfs -put -f par1.txt /user/hive/warehouse/big12.db/par1/prov=henan/city=kaifeng
  6. 復制數據到指定分區下

    # 分區表在嚴格模式下,必須至少指定一個靜態分區。
    $hive>insert into par1 partition(prov=‘hebei‘ , city) select 1 , ‘tom‘ , ‘cc‘;       
    # 指定了兩個都是動態分區(錯誤的 )
    $hive>insert into par1 partition(prov , city) select 10,‘tom10‘,56,‘Liaoning‘ , ‘DL‘;
    
    # 設置動態分區非嚴格模式
    $hvie>set hive.exec.dynamic.partition.mode=nonstrict ; 
  7. 動態分區模式

    動態分區有嚴格和非嚴格之分。嚴格模式下插入數據時至少有一個是靜態分區,非嚴格模式下都可以是動態分區。

    # 非嚴格
    $hive>set hive.exec.dynamic.partition.mode=nonstrict ; 
    # 嚴格
    $hive>set hive.exec.dynamic.partition.mode=strict ; 
  8. 關閉動態分區

    # true | false
    $hive>set hive.exec.dynamic.partition=true ;

10、桶表

桶表原理就是hash,針對文件進行劃分。分區表是針對目錄劃分。對記錄需要單條檢索的時候可以使用桶表。分桶的大小推薦我們每個buck數據量是blocksize的2倍。桶表不能使用load指令進行數據的加載。通過表數據復制方式實現桶表數據存儲。

  1. 創建桶表

    $hive>CREATE TABLE buck1(
    id int ,
    name string
    )
    CLUSTERED BY (id) INTO 3 BUCKETS
    ROW FORMAT DELIMITED
    FIELDS TERMINATED BY ‘,‘
    lines terminated by  ‘\n‘;
  2. 復制數據到桶表

    $hive>insert into buck1 select id,name from par1 ;

11、文件格式

在hive中列存儲格式的文件具有較好的性能,面向列的存儲將同一列的值連續存儲起來,當進行投影(查詢若幹字段,而不是全部字段)查詢時,可以發揮磁盤的線性讀寫,默認是文本文件。

  1. textfile

    文本文件,默認模式。

    # 創建表指定格式
    $hive>CREATE TABLE .. STORED AS textfile ;
    
    # 修改表,指定格式
    $hive>ALTER TABLE .. [PARTITION partition_spec] SET FILEFORMAT textfile ;

    ?

  2. sequencefile

    序列文件,key-value存儲方式。可以指定壓縮形式,有block、record、none。

  3. rcfile

    Record Columnar File,kv存儲,類似於sequencefile,將數據文件水平切割多個組。若幹group存放在一個hdfs中,先保存所有行的第一列,第二列,以此類推。該文件可切割.可以跳過不相關部分,更快得到數據,成本更低。

    通過CTAS方式創建RCFile文件:

    $hive>create table rcfile1 stored as rcfile as select * from buck1 ;
  4. orc

    Optimized Row Columnar,RCFile增強版。支持的大數據塊(256M)。和rcfile的不同是使用特殊的編碼器感知數據類型,並依據不同的類型進行壓縮優化。同時也存儲了基於column的一些基本的統計(MIN, MAX, SUM, and COUNT)信息,還有輕量級索引。支持範圍較窄,只有hive和pig。

    $hive>create table orc1 stored as orc as select * from buck1;
  5. parquet

    類似於orc,相對於orc文件格式,hadoop生態系統中大部分工程都支持parquet文件。

    $hive>create table parquet1 stored as parquet as select * from buck1;

12、事務支持

hive對事務的支持是有限制的,需要桶表+事務屬性+orc文件+事務控制。

  1. 創建orc文件格式的桶表,並指定支持事務

    $hive>create table tx(id int ,name string , age int)
    clustered by (id) into 2 buckets
    stored as orc TBLPROPERTIES(‘transactional‘=‘true‘);
  2. 設置hive相關的屬性支持

    $hive>SET hive.support.concurrency = true;
    SET hive.enforce.bucketing = true;
    SET hive.exec.dynamic.partition.mode = nonstrict;
    SET hive.txn.manager = org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;
    SET hive.compactor.initiator.on = true;
    SET hive.compactor.worker.threads = 1;
  3. 復制數據都事務表

    $hive>insert into tx select id , name , 18 from par1 ;

13、查詢

  1. 去重

    指定多個reduce有效,key進行hash處理,key只要相同,hash到同一reduce,因此可以使用多個reduce實現去重。

    $hive>set mapreduce.job.reduces= 3 ;
    $hive>select distinct id ,name from par1 ;
  2. 排序

    hive實現全排序有兩種方式,order by方式和sort by方式。order by使用reduce實現,導致數據傾斜。

    • order by

      $hive>select * from par1 order by id desc ;
    • sort by

      部分排序,在reduce端按照指定的key進行部分排序。以下語句在每個reduce內按照sal降序排列。

      $hive>create table tmp as select * from emp2 sort by sal desc ;
    • distribute by

      按照指定字段進行分發,就是分區過程,該語句需要在sort by之前。

      $hive>create table tmp3 as select * from emp2 distribute by dep sort by sal desc;
    • cluster by

      如果distribute by 和 sort by使用的是相同的字段,則可以直接使用cluster by。

      $hive>create table tmp4 as select * from emp2 cluster by sal desc ;
    • 對氣溫數據進行全排序

      年份升序全排序,年份內氣溫值降序排列。

      1. 創建表

        $hive>CREATE TABLE temps(
        year int,
        temp int
        )
        ROW FORMAT DELIMITED
        FIELDS TERMINATED BY ‘ ‘
        lines terminated by ‘\n‘;

        ?

      2. 加載數據

        $hive>load data 

        ?

      3. 執行查詢

        $hive>create table tmp5 as select * from temps distribute by case when year < 1930 then 0 when year > 1960 then 2 else 1 end sort by year asc , temp desc ;

        ?

hive基礎1