Spark开发-Spark和UDTF之间的介绍

built-in functions and user-defined functions (UDFs)

1.built-in functions

 01.Scalar Functions
   Array Functions eg:   array_contains(array, value)  array_max(array)
   Map Functions         map_keys(map)   map_values(map)
   Date and Timestamp Functions eg: 
                         current_timestamp()  date_trunc(fmt, ts) from_unixtime(unix_time, format)
						 to_unix_timestamp(timeExp[, format])   unix_timestamp([timeExp[, format]])
   JSON Functions     eg:  from_json  to_json  schema_of_json get_json_object  json_tuple
 02.Aggregate-like Functions
    Aggregate Functions  
	       eg:  avg(expr)  bit_xor(expr)  bool_or(expr)  collect_list(expr)  collect_set(expr)
		   count_if(expr)
    Window Functions
	       row_number()  dense_rank()  rank()  ntile(n)

Spark UDF

 Hive的情况:
  UDF:  Hive has two UDF  interfaces:  UDF  and GenericUDF
            UDF 重写 evaluate 方法
			GenericUDF 重写  initialize
  UDAF:	Hive has two UDAF interfaces:  UDAF and GenericUDAFResolver   < AbstractGenericUDAFResolver  GenericUDAFEvaluator>
  UDTF: GenericUDTF 
	 UDTF : while Hive UDAFs operate on multiple rows and return a single aggregated row as a result
	 UDTF : configure
 Spark的情况

 Spark中目前是有UDF UDAF 但目前不支持UDTF,使用的是Hive的UDTF,同时对于UDF的支持,在SparkSQL任务中支持也不是很好
 GenericUDTF
 了解Hive的 UDTF

Spark中对应的功能

map     :对集合中每个元素进行操作。              一对一,使用 map     方法
flatMap :对集合中每个元素进行操作然后再扁平化。  一变多,使用 flatMap 方法

Spark的UDTF

 POM文件
  	<dependency>
		<groupId>org.apache.hive</groupId>
		<artifactId>hive-exec</artifactId>
		<version>2.3.4</version>
		<scope>provided</scope>
	 </dependency>
 类
   org.apache.hadoop.hive.ql.udf.generic.GenericUDTF
重写的方法
   initialize   process  close
  //该方法中,指定输入输出参数:输入参数的ObjectInspector 与输出参数的StructObjectInspector
   abstract StructObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException;  
   //处理一条输入记录,输出若干条结果记录
   abstract void process(Object[] record) throws HiveException; 
   //当没有记录处理的时候该方法会被调用,用来清理代码或者产生额外的输出
   abstract void close() throws HiveException;

   Spark 2.X 内部不直接支持 udtf,     
   Spark 1.* 可以实现通过 hive 的 UDTF, 并注册函数实现
 使用:
    UDTF有两种使用方法,一种直接放到select后面,一种和lateral view一起使用
	  .enableHiveSupport()      //启用hive
	   //注册utdf算子,这里无法使用sparkSession.udf.register()
      spark.sql("CREATE TEMPORARY FUNCTION UserDefinedUDTF as 'com.zxc.sparkAppTest.udtf.UserDefinedUDTF'")
   GenericUDTF中有两个initialize方法: 重写其Hive GenericUDTF 底层的代码

参考:

 http://spark.apache.org/docs/latest/sql-ref-functions-builtin.html#array-functions
 https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF
 https://github.com/sunyaf/bitmapudf
 Hive Data Types – Primitive and Complex Data Types in Hive https://data-flair.training/blogs/hive-data-types/
 https://issues.apache.org/jira/browse/SPARK-21101
 spark调用hiveUDTF踩坑记录  https://blog.csdn.net/weixin_40206335/article/details/106591726
原文地址:https://www.cnblogs.com/ytwang/p/14025529.html