在星火-SQL创建用户定义的函数 [英] Creating User Defined Function in Spark-SQL

查看:119
本文介绍了在星火-SQL创建用户定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的火花和火花SQL和我正在试图使用SQL火花来查询一些数据。

I am new to spark and spark sql and i was trying to query some data using spark SQL.

我需要每月从中给出一个字符串的日期取。

I need to fetch the month from a date which is given as a string.

我觉得是不是可以直接从sparkqsl查询一个月,所以我想用Scala编写一个用户自定义的功能。

I think it is not possible to query month directly from sparkqsl so i was thinking of writing a user defined function in scala.

是否有可能写在UDF和sparkSQL如果可能的话有谁能够提出编写UDF的最佳方法。

Is it possible to write udf in sparkSQL and if possible can anybody suggest the best method of writing an udf.

请帮忙

推荐答案

您可以做到这一点,至少在过滤,如果你愿意使用语言集成查询。

You can do this, at least for filtering, if you're willing to use a language-integrated query.

有关包含数据的文件dates.txt:

For a data file dates.txt containing:

one,2014-06-01
two,2014-07-01
three,2014-08-01
four,2014-08-15
five,2014-09-15

只要你想你可以包在你的UDF尽可能多的斯卡拉日期魔法,但我会保持简单:

You can pack as much Scala date magic in your UDF as you want but I'll keep it simple:

def myDateFilter(date: String) = date contains "-08-"

如下设置了这一切 - 很多,这是从编程指南

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext._

// case class for your records
case class Entry(name: String, when: String)

// read and parse the data
val entries = sc.textFile("dates.txt").map(_.split(",")).map(e => Entry(e(0),e(1)))

您可以使用UDF作为其一部分的WHERE子句:

You can use the UDF as part of your WHERE clause:

val augustEntries = entries.where('when)(myDateFilter).select('name, 'when)

和看到的结果:

augustEntries.map(r => r(0)).collect().foreach(println)

请注意,我已经使用了其中,法的版本,宣布为在doc如下:

Notice the version of the where method I've used, declared as follows in the doc:

def where[T1](arg1: Symbol)(udf: (T1) ⇒ Boolean): SchemaRDD

因此​​,UDF只能取一个参数,但您可以撰写几。凡()调用多个列进行筛选。

So, the UDF can only take one argument, but you can compose several .where() calls to filter on multiple columns.

修改火花1.2.0(真是太1.1.0)

虽然它不是真正的记载,星火现在支持注册一个UDF,因此它可以从SQL查询。

While it's not really documented, Spark now supports registering a UDF so it can be queried from SQL.

以上UDF可以用注册:

The above UDF could be registered using:

sqlContext.registerFunction("myDateFilter", myDateFilter)

如果该表登记

sqlContext.registerRDDAsTable(entries, "entries")

它可以使用查询

sqlContext.sql("SELECT * FROM entries WHERE myDateFilter(when)")

有关详细信息,请参见这个例子

For more details see this example.

这篇关于在星火-SQL创建用户定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆