hive UDF詳解 例項

2021-07-31 13:41:48 字數 2362 閱讀 2738

udf可以直接應用於select語句,對查詢結果做格式化處理後輸出內容

操作作用於單個資料行,且產生了乙個資料行作為輸出

實現udf(user-defined-function)

需要繼承org.apache.hadoop.hive.ql.udf

需要實現evaluate函式(evaluate函式支援過載)

實現udf查詢hive表中array型別列的值中是否包含某一項

select find_in_array(column, 『key』) from users;

# cat /root/person.txt 

zhangsan beijing,shanghai,tianjin,hangzhou

lisi changchu,chengdu,wuhan

create

table users(name string, worklocations array) row format delimited fields terminated by

'\t' collection items terminated by

',';

load data local inpath '/root/person.txt ' overwrite into

table users;

hive array基本操作看這裡建表+查詢+修改

public

class

find_in_array

extends

udfelse

}public string evaluate(string keywords,arraylistcolumn,string name)else}}

編寫完成後,匯出jar包

方法1

會話結束後,函式會自動銷毀,所以每次開啟新的會話,都要重新add jar並create temporary function

hive> add jar /root/find_in_array.jar;

added [/root/find_in_array.jar] to class path

added resources: [/root/find_in_array.jar]

hive> create temporary function find_in_array as 'com.neu.hive.udf.find_in_array';

oktime taken: 0.448 seconds

hive> select find_in_array('beijing',worklocations,name)from users;

okzhangsan

null

time taken: 0.578 seconds, fetched: 2 row(s)

hive> select find_in_array('beijing',worklocations)from users;

ok["beijing","shanghai","tianjin","hangzhou"]

null

time taken: 0.049 seconds, fetched: 2 row(s)

方法2

使用hive -i引數在進入hive時自動初始化,會話結束後,函式也會自動銷毀

# cat hive_init 

add jar /root/find_in_array.jar;

create

temporary function topk as

'com.neu.hive.udf.find_in_array';

# hive -i hive_init

方法3

將udf註冊為內建函式,如果不是特別通用,固化下來的函式,不要使用這種方法

報以下錯誤,一定要有evaluate函式,且引數要匹配,要仔細檢查!

hive> select find(name,users.worklocations)from users;

failed: semanticexception [error 10014]: line 1:7 wrong arguments 『worklocations』: no matching method for class com.neu.hive.udf.find_in_array with (string, array). possible choices:

hive udf相關操作

1,在 伺服器上傳本地檔案hiveudf 1.1.1.jar到hdfs目錄 hivejar下,這個可以永久使用 hdfs dfs put opt hiveudf 0.0.1.jar hivejar2,建立udf臨時函式 add jar hdfs hiveudf hiveudf 2.5 jar wit...

Hive UDF函式使用

udf函式 udf user defined functions 即是使用者定義的hive函式。hive自帶的函式並不能完全滿足業務需求,這時就需要我們自定義函式了 開發自定義udf函式需要繼承 org.apache.hadoop.hive.ql.exec.udf 類,並實現evaluate函式 實...

Hive UDF開發案例

bin hive中操作 臨時函式的使用 add jar home hadoop lib train 1.0 snapshot.jar 將上傳的jar包匯入到classpath變數裡 list jars 檢視匯入的jar包 create temporary function say hello as ...