Spark (18) Custom function UDF for Sparksql

Source: Internet
Author: User

In Spark, custom functions in hive are also supported. The custom function can be broadly divided into three types:

    • UDF (User-defined-function), which is the most basic custom function, similar to to_char,to_date, etc.
    • UDAF (user-defined Aggregation funcation), user-defined aggregate function, similar to SUM,AVG used after group by
    • UDTF (user-defined table-generating Functions), user-defined build function, a bit like the flatmap inside the stream

Customizing a UDF function requires inheriting the Userdefinedaggregatefunction class and implementing 8 of these methods

Example

Import Org.apache.spark.sql.Rowimport org.apache.spark.sql.expressions. {mutableaggregationbuffer, Userdefinedaggregatefunction}import org.apache.spark.sql.types. {DataType, StringType, Structfield, structtype}object getdistinctcityudf extends userdefinedaggregatefunction{/** * output     Data type * */override Def Inputschema:structtype = Structtype (Structfield ("status", Stringtype,true):: Nil)/** * Cache Field Type * */override Def Bufferschema:structtype = {Structtype (Structfield ("buffer_city _info ", Stringtype,true)))}/** * Output Result type * */override def Datatype:datatype = stringtype/** * input type and output type is a * */override def Deterministic:boolean = true/** * Initialize secondary fields * */override Def initialize (Buffer:mutableaggrega  Tionbuffer): Unit = {buffer.update (0, "")}/** * Modify the value of the secondary field * */override def update (Buffer:mutableaggregationbuffer, Input:row): Unit = {//Get last value var last_str = buffer.getstring (0)//Get current value val current_str = Input.getstring (0)//Determines whether the last value contains the current value if (!last_str.contains (CURRENT_STR)) {//determines if the value is the first, or if the value is the one that goes if the    if (Last_str.equals (")) {last_str = current_str}else{last_str + =", "+ Current_str}} Buffer.update (0,LAST_STR)}/** * Merge partition results * Buffer1 is the result of machine HADOOP1 * Buffer2 is the result of machine HADOOP2 * */override def merge (bu Ffer1:mutableaggregationbuffer, buffer2:row): Unit = {var buf1 = buffer1.getstring (0) Val buf2 = Buffer2.getstrin         G (0)//BUF2 the data that exists inside the BUF1 and append the data that is not inside to the BUF1//buf2 data according to, Shard for (S <-buf2.split (",")) {if (!buf1.contains (s)) { if (Buf1.equals (")) {Buf1 = s}else{buf1 + = s}}} buffer1.update (0,b UF1)}/** * Final Calculation result * */override def evaluate (Buffer:row): any = {buffer.getstring (0)}}

Registering a custom UDF function as a temporary function

def main (args:array[string]): Unit = {    /**      * First step to create a program entry */    val conf = new sparkconf (). Setappname ("Aralho Tproductspark ")    val sc = new Sparkcontext (conf)    val hivecontext = new Hivecontext (SC)
Register as temporary function hiveContext.udf.register ("get_distinct_city", GETDISTINCTCITYUDF)//Register as temporary function HiveContext.udf.register ("Get_product_status", (str:string) =>{ var status = 0 for (s <-str.split (",")) { if (s.contains ("Product_status")) { status = S.split (":") (1). ToInt } } )}

Spark (18) Custom function UDF for Sparksql

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.