天天看點

Hive資料類型、 explode、自定義UDFHive資料類型、 explode、自定義UDF

Hive資料類型、 explode、自定義UDF

一、基本類型

Hive資料類型、 explode、自定義UDFHive資料類型、 explode、自定義UDF

二、複雜類型

Hive資料類型、 explode、自定義UDFHive資料類型、 explode、自定義UDF

三、數組類型 array

  案例一、

  中繼資料:

   100,200,300

   200,300,500

  建表語句:create external table ex(vals array) row format delimited fields terminated by ‘\t’ collection items terminated by ‘,’ location ‘/ex’;

  查詢語句:

   查詢每行數組的個數 select size(vals) from ex;

   select vals[0] from ex;查詢的是第一行的資料。

  注:hive 内置函數不具備查詢某個具體行的數組元素。需要自定義函數來實作

  案例二、

  中繼資料:

   100,200,300 tom,jary

   200,300,500 rose,jack

  建表語句:create external table ex1(info1 array,info2 array) row format delimited fields terminated by ‘\t’ collection items terminated by ‘,’ location

‘/ex’;

四、map類型

  案例一、

  中繼資料:

   tom,23

   rose,25

   jary,28

  建表語句:

   create external table m1 (vals map<string,int>) row format delimited fields terminated by ‘\t’ map keys terminated by ‘,’ location ‘/map’;

  如果是map類型,列分隔符必須是\t

  查詢語句:select vals[‘tom’] from ex;

五、struct 類型(對象類型)

  中繼資料:

   tom 23

   rose 22

   jary 26

  建表語句:

   create external table ex (vals structname:string,age:int)row format delimited collection items terminated by ‘,’ location ‘/m1’;

  查詢語句:select vals.age from s1 where vals.name=‘tom’;

六、collect_set

  collect_set 函數用于資料去重,并将結果形成數組傳回

七、 explode

  explode 指令可以将行資料,按指定規則切分出多行

  原資料:

   100,200,300

   200,300,500

  建立表::create external table ex1 (num string) location ‘/ex’;

  注:用explode做行切分,注意表裡隻有一列,并且行資料是string類型,因為隻有字元類型才能做切分。

  通過explode指令來做行切分:執行:select explode(split(num,’,’)) from ex1;

八、UDF

  如果hive的内置函數不夠用,我們也可以自己定義函數來使用,這樣的函數稱為hive的使用者自定義函數,簡稱UDF。

  實作步驟:

   1.建立java工程,導入hive相關包,導入hive相關的lib。

   2.建立類繼承UDF

   3.自己編寫一個evaluate方法,傳回值和參數任意

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

public class ToUpper extends UDF{
	public String evaluate(String str){
		return str.toUpperCase();
	}
}
           

4.為了能讓mapreduce處理,String要用Text處理。

  5.将寫好的類打成jar包,上傳到linux中

  6.在hive指令行下,向hive注冊UDF:add jar /xxxx/xxxx.jar

  7.在hive指令行下,為目前udf起一個名字:create temporary function fname as ‘類的全路徑名’;

  8.之後就可以在hql中使用該自定義函數了。

繼續閱讀