1. 程式人生 > >大資料技術學習筆記之hive框架基礎2-hive中常用DML和UDF和連線介面使用

大資料技術學習筆記之hive框架基礎2-hive中常用DML和UDF和連線介面使用

一、分割槽表的介紹及使用
    -》需求:統計每一天的PV,UV,每一天分析前一天的資料
        -》第一種情況:每天的日誌儲存在同一個目錄中
            /logs/20170209.log
                  20170210.log
                  20170211.log
            
            -》預處理:將日期欄位提取轉換成yyyyMMdd的格式
            -》資料分析:
                select * from logs where date='20170211';
                先載入所有資料,然後再進行過濾
        -》第二種情況:每天的日誌儲存在以當天日期命名的檔案目錄中
            /logs/20170209/20170209.log
                  20170210/20170210.log
                  20170211/20170211.log
                  
            -》資料分析:
                select * from logs where date='20170211';
                
                先進行過濾,只加載需要的資料
                
    -》hive分割槽表實現的功能:
        -》將表中的資料進行分割槽,在進行分割槽檢索時,直接載入對應分割槽的資料
        -》對於HDFS來說,多了一級目錄    
        -》對於資料處理來說,直接處理了需要的資料,提前進行了過濾
        
        
    -》分割槽表的使用
        -》建立分割槽表:PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)
            -》分割槽表中的欄位是邏輯的欄位,資料檔案中沒有實際的欄位儲存
        create table emp_part(
        empno int,
        ename string,
        job string,
        mgr int,
        hiredate string,
        sal double,
        comm double,
        deptno int
        )
        partitioned by (date string)
        row format delimited fields terminated by '\t';
        load data local inpath '/opt/datas/emp.txt' into table emp_part partition (date='20170211');
        load data local inpath '/opt/datas/emp.txt' into table emp_part partition (date='20170212');

        select * from emp_part where date='20170212';
    -》企業中:分割槽表+外部表
    -》多級分割槽
        create table emp_part_2(
        empno int,
        ename string,
        job string,
        mgr int,
        hiredate string,
        sal double,
        comm double,
        deptno int
        )
        partitioned by (date string,hour string)
        row format delimited fields terminated by '\t';
        load data local inpath '/opt/datas/emp.txt' into table emp_part_2 partition (date='20170211',hour='00');
        
二、hive表資料的匯入匯出
    -》匯入
        -》載入本地檔案到hive:拷貝檔案
            load data local inpath 'linux_filepath' into table tablename;
            load data local inpath '/opt/modules/hive-0.13.1-bin/student.txt' into table tmp2_table;
            -》應用場景:常見的情況,一般用於日誌檔案的直接匯入
        -》載入HDFS檔案到hive:移動檔案
            load data  inpath 'hdfs_filepath' into table tablename;
            -》應用場景:本地資料儲存檔案比較大的情況
        -》覆蓋表中的資料
            load data local inpath '/opt/modules/hive-0.13.1-bin/student.txt' overwrite into table tmp2_table;
            -》應用場景:一般用於臨時表資料的匯入
        -》建立表時通過select載入資料
            create table tmp2_table2 as select * from tmp2_table;
            -》應用場景:常用於臨時表反覆使用,作為資料分析結果的儲存
        -》建立表時通過location載入資料
            create tabletmp2_table3(col_comment……) location 'hdfs_filepath';
            -》應用場景:固定的資料採集時指定hdfs的資料目錄
        -》建立表以後,通過insert載入資料
            insert into|overwrite table tbname select *……
            create table tmp2_table4(
            num string ,
            name string
            )
            row format delimited fields terminated by '\t'
            stored as textfile;
            insert into table tmp2_table4 select * from tmp2_table;
            -》用於資料分析結果的匯入或者儲存
    -》匯出
        -》通過insert命令進行匯出
            insert overwrite [local] directory 'path' select *……
            -》匯出到本地目錄
                insert overwrite local directory '/opt/datas/tmp2_table' select * from tmp2_table2;
                insert overwrite local directory '/opt/datas/tmp2_table' row format delimited fields terminated by '\t' select * from tmp2_table2;
            -》匯出到HDFS
                insert overwrite directory '/tmp2_table' select * from tmp2_table2;
                -》匯出到hdfs不支援分隔符的指定
                insert overwrite directory '/tmp2_table' row format delimited fields terminated by '\t' select * from tmp2_table2;
        -》通過Hadoop的hdfs命令中的get操作匯出資料
        -》通過hive -e 或者 -f 執行hive的語句,將資料執行的結果進行重定向儲存即可
        -》sqoop框架將資料匯出到關係型資料庫
    -》import和export:用於hive表的備份
        -》export table tmp2_table to '/export';
        -》import table tmp2_table5 from '/export';
        
三、hive的常用語句及UDF
    -》基本語句
        -》欄位的查詢
        -》where、limit、distinct
            -》查詢部門編號是30的員工
                select empno,ename,deptno from emp where deptno='30';
            -》檢視前3條記錄
                select * from  emp limit 3;
            -》查詢當前有哪些部門
                select distinct deptno from emp;
        -》between and,> <、is null ,is not null,in,not in
            -》查詢員工編號大於7500
                select * from emp where empno>7500;
            -》查詢薪資在2000到3000之間
                select * from emp where sal between 2000 and 3000;
            -》查詢獎金不為空的員工
                select * from emp where comm is not null;
        -》聚合函式max、min、avg、count、sum
            -》select count(1) cnt from emp;
            -》select max(sal) max_sal from emp;
            -》select avg(sal) max_sal from emp;
        -》group by ,having
            -》求每個部門的平均工資
                select deptno,avg(sal) from emp group by deptno;
            -》求部門平均工資大於2000的
                select deptno,avg(sal) avg from emp group by deptno having avg >2000;
        -》join
            -》等值join(inner join):兩邊都有的值進行join
                select a.empno,a.ename,a.sal,b.deptno,b.dname from emp a inner join dept b on a.deptno=b.deptno;
            -》left join:以左表的值為基準
                select a.empno,a.ename,a.sal,b.deptno,b.dname from emp a left join dept b on a.deptno=b.deptno;
            -》right join:以右表的值為基準
                select a.empno,a.ename,a.sal,b.deptno,b.dname from emp a right join dept b on a.deptno=b.deptno;
            -》full join:以兩張表中所有的值為基準
                select a.empno,a.ename,a.sal,b.deptno,b.dname from emp a full join dept b on a.deptno=b.deptno;
                
    -》hive中reduce的配置
        In order to change the average load for a reducer (in bytes):
          set hive.exec.reducers.bytes.per.reducer=<number>
        In order to limit the maximum number of reducers:
          set hive.exec.reducers.max=<number>
        In order to set a constant number of reducers:
          set mapreduce.job.reduces=<number>
    -》hive中的四種排序
        -》order by:對某一列進行全域性排序
            select empno,ename,deptno,sal from emp order by sal desc;
            insert overwrite local directory '/opt/datas/order' select empno,ename,deptno,sal from emp order by sal desc;
        -》sort by:對每個reduce進行內部排序,如果只有一個reduce,等同於order by
            set mapreduce.job.reduces=2
            insert overwrite local directory '/opt/datas/sort' select empno,ename,deptno,sal from emp sort by sal desc;
        -》distribute by:對資料按照某個欄位進行分割槽,交給不同的reduce進行處理
                            一般與sortby連用,必須放在sort by前面
            insert overwrite local directory '/opt/datas/distribute' select empno,ename,deptno,sal from emp distribute by empno sort by sal desc;
        -》cluster by:當我們的distribute by與sort by使用的是同一個欄位時,可用cluster by
            insert overwrite local directory '/opt/datas/distribute' select empno,ename,deptno,sal from emp cluster by sal desc;
    -》hive中的分析函式與視窗函式
        https://cwiki.apache.org/confluence/display/Hive/LanguageManual+WindowingAndAnalytics
        
        -》功能:可以對分組後的資料進行組內每行的處理
        -》格式:f_name() over (partition by col order by col)
        -》演示:
            -》對emp表進行薪資降序排列
                select empno,ename,deptno,sal from emp order by sal desc;
            -》對emp表進行每個部門的薪資降序排列,顯示序號
                select empno,ename,deptno,sal,ROW_NUMBER() over (partition by deptno order by sal desc) as number from emp;
            -》顯示每個部門最高的薪資
                select empno,ename,deptno,sal,max(sal) over (partition by deptno order by sal desc) as max_sal from emp;
        -》分析函式:
            -》row_number()
            -》rand()
        -》視窗函式
            -》lead
                -》格式:lead(value1,value2,value3)
                    value1:所要選取的列
                    value2: 偏移量
                    value3:超出視窗的預設值
                -》功能:顯示目標列的後幾個(偏移量)值
                    select empno,ename,deptno,sal,lead(sal,1,0) over (partition by deptno order by sal desc)  from emp;
            -》lag
                -》格式:lag(value1,value2,value3)
                    value1:所要選取的列
                    value2: 偏移量
                    value3:超出視窗的預設值
                -》功能:顯示目標列的前幾個(偏移量)值
                    select empno,ename,deptno,sal,lag(sal,1,0) over (partition by deptno order by sal desc)  from emp;
            -》first_value
            -》last_value
    -》hive中的UDF
        -》user define function:使用者自定義函式
        -》型別:
            -》UDF:一進一出
            -》UDAF:多進一出
            -》UDTF: 一進多出
        -》實現UDF
            -》編寫UDF程式碼
                -》繼承UDF類
                -》實現至少一個或者多個evaluate方法
                -》必須有返回值,可以為null,但是不能是void型別
                -》程式碼中儘量使用Hadoop的資料型別
                    -》Text
                    -》writable
            -》打成jar包
            -》新增到hive的classpath中
            -》在hive中建立方法
            -》呼叫方法
        -》編寫UDF,實現日期的轉換
            31/Aug/2015:00:04:37 +0800    -》        2015-08-31 00:04:37
            -》將hive的和Hadoop依賴新增到pom檔案
                <dependency>
                  <groupId>org.apache.hive</groupId>
                  <artifactId>hive-exec</artifactId>
                  <version>0.13.1</version>
                </dependency>
                <dependency>
                  <groupId>org.apache.hive</groupId>
                  <artifactId>hive-jdbc</artifactId>
                  <version>0.13.1</version>
                </dependency>
            -》建立UDF程式碼
            -》打包
            -》在hive中新增
                add jar /opt/datas/dateudf.jar;
            -》在hive中建立方法
                create temporary function dateudf as 'com.hpsk.bigdata.hive.udf.DateFormat';
            -》使用
                select dateudf('31/Aug/2015:00:04:37 +0800') date from emp;

四、hive的連線方式
    -》hive shell
        -》-e
        -》-f
    -》hiveserver2:將hive的服務變成服務端,可以通過客戶端進行連線
        -》bin/hiveserver2
            -》啟動在後臺執行:bin/hiveserver2 &
        -》beeline
            -》bin/beeline -h
                -》第一種使用方式:
                       -u <database url>               the JDBC URL to connect to
                       -n <username>                   the username to connect as
                       -p <password>                   the password to connect as
                    bin/beeline -u jdbc:hive2://bigdata-training01.hpsk.com:10000 -n hpsk -p hpsk
                -》第二種使用方式
                    bin/beeline
                    !connect jdbc:hive2://bigdata-training01.hpsk.com:10000
        -》jdbc方式
            https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients#HiveServer2Clients-JDBC
            
五、hive語句的解析
    -》執行一條SQL語句
        -》連線元資料,判斷資料庫是否存在
        -》判斷表或者分割槽是否存在
        -》如果存在找到對應的HDFS的目錄,傳遞給MapReduce作為輸入
        -》DBS:儲存了所有資料庫的資訊
        -》TBLS:儲存了所有表的資訊
        -》PARTITIONS:儲存了所有分割槽的資訊
        -》SDS:儲存了所有表和分割槽在hdfs上所對應的目錄
    -》fetch task
        <property>
          <name>hive.fetch.task.conversion</name>
          <value>minimal</value>
          <description>
            Some select queries can be converted to single FETCH task minimizing latency.
            Currently the query should be single sourced not having any subquery and should not have
            any aggregations or distincts (which incurs RS), lateral views and joins.
            1. minimal : SELECT STAR, FILTER on partition columns, LIMIT only
            2. more    : SELECT, FILTER, LIMIT only (TABLESAMPLE, virtual columns)
          </description>
        </property>
    -》hive中的虛擬列
        -》INPUT__FILE__NAME:該記錄所在的檔案的地址
        -》BLOCK__OFFSET__INSIDE__FILE: 該記錄在檔案塊中的偏移量
        -》ROW__OFFSET__INSIDE__BLOCK: 行的偏移量,預設不啟用
              <name>hive.exec.rowoffset</name>
              <value>false</value>
    -》嚴格模式
        <property>
          <name>hive.mapred.mode</name>
          <value>nonstrict</value>
          <description>The mode in which the Hive operations are being performed.
             In strict mode, some risky queries are not allowed to run. They include:
               Cartesian Product.
               No partition being picked up for a query.
               Comparing bigints and strings.
               Comparing bigints and doubles.
               Orderby without limit.
          </description>
        </property>
        -》開啟嚴格模式後的限制
            -》如果分割槽表不加分割槽過濾,不允許執行
            -》限制笛卡爾積的執行,使用join時不使用on
            -》限制bigint與string型別的比較
            -》限制bigint與double型別的比較
            -》使用order by時,如果不用limit,也不允許執行
    -》語句解析命令:explain
        -》將語句解析成語法樹