hive基础1

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 ;

        ?

原文地址:https://www.cnblogs.com/star521/p/9702954.html

时间: 2024-08-09 06:42:33

hive基础1的相关文章

Hive基础之Hive体系架构&amp;运行模式&amp;Hive与关系型数据的区别

Hive架构 1)用户接口: CLI(hive shell):命令行工具:启动方式:hive 或者 hive --service cli ThriftServer:通过Thrift对外提供服务,默认端口是10000:启动方式:hive --service hiveserver WEBUI(浏览器访问hive):通过浏览器访问hive,默认端口是9999:启动方式:hive --service hwi 2)元数据存储(Metastore):启动方式:hive -service metastore

Hive基础之Hive是什么以及使用场景

Hive是什么1)Hive 是建立在Hadoop (HDFS/MR)上的用于管理和查询结果化/非结构化的数据仓库:2)一种可以存储.查询和分析存储在Hadoop 中的大规模数据的机制:3)Hive 定义了简单的类SQL 查询语言,称为HQL,它允许熟悉SQL 的用户查询数据:4)允许用Java开发自定义的函数UDF来处理内置无法完成的复杂的分析工作:5)Hive没有专门的数据格式(分隔符等可以自己灵活的设定): ETL的流程(Extraction-Transformate-Loading):将关

Hive基础之Hive环境搭建

Hive默认元数据信息存储在Derby里,Derby内置的关系型数据库.单Session的(只支持单客户端连接,两个客户端连接过去会报错): Hive支持将元数据存储在关系型数据库中,比如:Mysql/Oracle: 本案例采用的是将hive的元数据存储在MySQL中,故需要先安装MySQL数据库,使用的是CentOS6.4版本. MySQL安装 采用yum安装方式安装: yum install mysql #安装mysql客户端 yum install mysql-server #安装mysq

Hive基础之各种排序的区别

order by 1.order by会对输入做全局排序,因此只有一个reducer(多个reducer无法保证全局排序): 只有一个reducer会导致当输入规模较大时,需要较长的计算时间,速度很非常慢: 2.hive.mapred.mode(默认值是nonstrict)对order by的影响 1)当hive.mapred.mode=nonstrict时,order by和关系型数据库中的order by功能一致,按照指定的某一列或多列排序输出: 2)当hive.mapred.mode=st

【Hive】Hive 基础

Hive架构: Hive基础 1 概念 1.1 简介 1.1.1 hive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张数据库表, 并提供简单的sql查询功能,可以将sql语句转换为MapReduce任务进行运行.--OLAP 1.2 背景 1.2.1 OLAP逻辑和SQL一样大体一致,可以将这些逻辑转化为对应的MR,不需要每种类型的查询分析都重复写MR 1.2.2 Facebook开发通用的MR程序框架,对外使用SQL接口,框架就是Hive 1.3 官网 1.3.1 h

Hive基础之Hive表常用操作

本案例使用的数据均来源于Oracle自带的emp和dept表 创建表 语法: CREATE [EXTERNAL] TABLE [IF NOT EXISTS] [db_name.]table_name [(col_name data_type [COMMENT col_comment], ...)] [COMMENT table_comment] [PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)] [CLUSTERED

Hive基础之Hive的复杂类型

Array 一组有序字段,字段的类型必须相同.Array(1,2) create table hive_array(ip string, uid array<string>) row format delimited fields terminated by ',' collection items terminated by '|' stored as textfile; load data local inpath "/home/spark/software/data/hive_

Hive基础之Hive的存储类型

Hive常用的存储类型有: 1.TextFile: Hive默认的存储类型:文件大占用空间大,未压缩,查询慢: 2.Sequence File: 3.RCFile:facebook开发的一个集行存储和列存储的优点于一身,压缩比更高,读取列更快,它在mr环境中大规模数据处理中扮演着重要的角色:是一种行列存储相结合的存储方式,首先它将数据按行分块,保证同一个record在一个块中,避免读取一个记录需要读取多个record:一般情况下,hive表推荐使用RCFile: RCFile案例: 创建表: c

hive基础2

RDBMS OLTP. relation database management system,关系型数据库管理系统. 支持事务(acid) 延迟低 安全行 V variaty : 多样性. hive mr,sql 开发效率高. 数据仓库. 数据库: //OLTP OLTP //online transaction process, OLAP //online analyze process,在线分析处理 , 很多分析函数 //rank | lag | lead | .. | cube | ro