Hive的使用

    Hive是一个基于hadoop平台的数据仓库工具,主要对海量数据进行统计分析

    1、运行模式(集群与本地)

        1.1、集群模式:>SET mapred.job.tracker=cluster

        1.2、本地模式:>SET mapred.job.tracker=local

    2、访问Hive的3钟方式

        2.1、终端访问

            #hive  或者  #hive --service cli  

        2.2、web访问,端口9999

            #hive --service hwi &

        2.3、hive远程服务,端口10000

            #hive --service hiveserver &

    3、数据类型

       3.1、基本数据类型 :    

            数据类型
            占用长度
            tinyint
      1byte(-128~127)
            smallint
      2byte(-2^16 ~ 2^16-1)
            int
      4byte(-2^31 ~ 2^31-1)
            bigint
      8byte(-2^63 ~ 2^63-1)
            float
      4byte单精度
            double
      8byte双精度
            string

            boolean

        3.2、复合数据类型:ARRAY,MAP,STRUCT,UNION

    4、数据存储

        4.1、基于HDFS

        4.2、存储结构:database 、table 、file 、view

        4.3、指定行、列分隔符即可解析数据

    5、基本操作

        5.1、创建数据库:>create database db_name

        5.2、指定数据库:>use db

        5.3、显示表:show tables;

        5.4、创建表

                5.4.1、内部表(默认):create table table_name(param_name type1,param_name2 type2,...) row format delimited fields terminated by '分隔符';

                 例:create table trade_detail(id bigint, account string, income double, expenses double, time string) row format delimited fields terminated by '\t';

                内部表类似数据库表,存储在HDFS上(位置通过hive.metastore.warehouse.dir参数查看,除了外部表以外都保存在此处的表),表被删除时,表的元数据信息一起被删除。

                加载数据:load data local inpath 'path' into table table_name;

                5.4.2、分区表:create table table_name(param_name type1,param_name2 type2,...) partitioned by (param_name type) row format delimited fields terminated by '分隔符';

                例:create table td_part(id bigint, account string, income double, expenses double, time string) partitioned by (logdate string) row format delimited fields terminated by '\t';

                和普通表的区别:各个数据划分到不同的分区文件,表中的每一个partition对应表下的一个目录,尽管

                加载数据:load data local inpath 'path' into table table_name partition (parti_param1='value',parti_param2='value',..); 

                添加分区:alter table partition_table add partition (daytime='2013-02-04',city='bj');

                删除分区:alter table partition_table drop partition (daytime='2013-02-04',city='bj'),元数据和数据文件被删除,但是目录还存在

                5.4.3、外部表:create external table td_ext(id bigint, account string, income double, expenses double, time string) row format delimited fields terminated by '\t' location 'hdfs_path';

                加载数据:load data inpath 'hdfs_path' table_name;

                5.4.4、桶表:是对数据进行哈希取值,然后放到不同文件中存储。
                创建表:create table bucket_table(id string) clustered by(id) into 4 buckets;

                加载数据:

                        set hive.enforce.bucketing = true;

                        必须先把以上的操作执行才能加载数据
                        insert into table bucket_table select name from stu;    
                        insert overwrite table bucket_table select name from stu;

                数据加载到桶表时,会对字段取hash值,然后与桶的数量取模。把数据放到对应的文件中。

                对数据抽样调查:select * from bucket_table tablesample(bucket 1 out of 4 on id);
        6、创建视图:CREATE VIEW v1 AS select * from t1;

        7、修改表:alter table tb_name add columns (param_name,type);
        8、删除表:drop table tb_name;

        9、数据导入

            9.1、加载数据:LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE]     INTO TABLE tablename     [PARTITION (partcol1=val1, partcol2=val2 ...)]

                    数据加载到表时,不会对数据进行转移,LOAD操作只是将数据复制到HIVE表对应的位置       
           9.2、Hive中表的互导:INSERT OVERWRITE TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement FROM from_statement
            9.3、create as :CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name  (col_name data_type, ...)    …AS SELECT * FROM TB_NAME;

        10、查询

            10.1、语法结构

                        SELECT [ALL | DISTINCT] select_expr, select_expr, ...
                        FROM table_reference
                        [WHERE where_condition]
                        [GROUP BY col_list]
                        [ CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list] | [ORDER BY col_list] ]
                        [LIMIT number]

            10.2、partition查询

                        利用分区剪枝(input pruning)的特性,类似“分区索引”,只有当语句中出现WHERE才会启动分区剪枝

            10.3、LIMIT Clause

                        Limit 可以限制查询的记录数。查询的结果是随机选择的。语法:SELECT * FROM t1 LIMIT 5
            10.4、Top N
                        SET mapred.reduce.tasks = 1   SELECT * FROM sales SORT BY amount DESC LIMIT 5

        11、表连接

            11.1、内连接:select b.name,a.* from dim_ac a join acinfo b on (a.ac=b.acip) limit 10;
            11.2、左外连接:select b.name,a.* from dim_ac a left outer join acinfo b on a.ac=b.acip limit 10;

        12、Java客户端

            12.1、启动远程服务#hive --service hiveserver

            12.2、相关代码     

Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive://192.168.1.102:10000/wlan_dw", "", "");
Statement stmt = con.createStatement();
String querySQL="SELECT * FROM wlan_dw.dim_m order by flux desc limit 10";

ResultSet res = stmt.executeQuery(querySQL);  

while (res.next()) {
    System.out.println(res.getString(1) +"\t" +res.getLong(2)+"\t" +res.getLong(3)+"\t" +res.getLong(4)+"\t" +res.getLong(5));
}

        13、自定义函数(UDF)

            13.1、UDF函数可以直接应用于select语句,对查询结构做格式化处理后,再输出内容。
            13.2、编写UDF函数的时候需要注意一下几点:
                a)自定义UDF需要继承org.apache.hadoop.hive.ql.UDF。
                b)需要实现evaluate函数,evaluate函数支持重载。

            13.3、步骤
                a)把程序打包放到目标机器上去;
                b)进入hive客户端,添加jar包:hive>add jar /run/jar/udf_test.jar;
                c)创建临时函数:hive>CREATE TEMPORARY FUNCTION add_example AS 'hive.udf.Add';
                d)查询HQL语句:
                    SELECT add_example(8, 9) FROM scores;
                    SELECT add_example(scores.math, scores.art) FROM scores;
                    SELECT add_example(6, 7, 8, 6.8) FROM scores;
                e)销毁临时函数:hive> DROP TEMPORARY FUNCTION add_example;
                注:UDF只能实现一进一出的操作,如果需要实现多进一出,则需要实现UDAF

            13.4、代码

            

package cn.itheima.bigdata.hive;

import java.util.HashMap;

import org.apache.hadoop.hive.ql.exec.UDF;

public class AreaTranslationUDF extends UDF{
    
    private static HashMap<String, String> areaMap = new HashMap<String, String>();
    
    static{
        
        areaMap.put("138", "beijing");
        areaMap.put("139", "shanghai");
        areaMap.put("137", "guangzhou");
        areaMap.put("136", "niuyue");
        
    }

    //用来将手机号翻译成归属地,evaluate方法一定要是public修饰的,否则调不到
    public String evaluate(String phonenbr) {

        String area = areaMap.get(phonenbr.substring(0,3));
        return area==null?"other":area;

    }
    
    //用来求两个字段的和
    public int evaluate(int x,int y){
        
        return x+y;
    }

}


你可能感兴趣的:(mapreduce,hadoop,hive)