温馨提示  2024年 6月我们已经停止开发者板块文章内容更新,谢谢来访。存档数据
知识 2023-08-27 33 次阅读

怎么实现spark schemardd隐式转换

   

今天就跟大家聊聊有关怎么实现spark schemardd隐式转换,可能很多朋友都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据本文可以有所收获。

schemardd在spark sql中已经被我们使用到,本文简单地介绍一下如果将标准的rdd(org.apache.spark.rdd.rdd)转换成schemardd,并进行sql相关的操作。

01/**  

这是因为people是普通的rdd,而registertemptable函数不属于rdd类,只有通过schemardd的实例才可以调用,所以这么调用会出现错误,解决方案有两个
  (1)registertemptable函数是sqlcontext类中的,所以我们可将people转换成schemardd,如下

02 * user: 过往记忆03 * date: 14-12-1604 * time: 下午10:1605 * bolg: http://www.iteblog.com06 * 本文地址http://www.iteblog.com/archives/122407 * 过往记忆博客,专注于hadoop、hive、spark、shark、flume的技术博客,大量的干货08 * 过往记忆博客微信公共帐号iteblog,hadoop09 */10scala> val peopleschema =sqlcontext.createschemardd(people)11peopleschema:org.apache.spark.sql.schemardd =12schemardd[29] at rdd at schemardd.scala:10313==query plan ==14==physical plan ==15existingrdd [name#4,age#5], mappartitionsrdd[28] at16 mappartitions at basicoperators.scala:21717 18scala> peopleschema.registertemptable(people)19warning:there were 1deprecation warning(s); re-run with-deprecation fordetails

  这么调用就可以将people转成schemardd。
  (2)、上面的方法是通过显示地调用sqlcontext.createschemardd将普通的rdd转成schemardd。其实我们还可以借助scala的隐式语法来进行转换。我们先来看看createschemardd函数的定义

1/**2* creates a schemardd from an rdd of case classes.3*4* @group userf5*/6implicitdefcreateschemardd[a <:product:typetag](rdd:rdd[a]) ={7    sparkplan.currentcontext.set(self)8    newschemardd(this, sparklogicalplan(existingrdd.fromproductrdd(rdd))(self))9}

  在定义createschemardd的时候用到了implicit 关键字,所以我们在使用的时候可以借助下面语句使用

1scala> import sqlcontext.createschemardd2import sqlcontext.createschemardd3 4scala> people.registerastable(people)5warning:there were 1deprecation warning(s); re-run with-deprecation fordetails

  这样就隐身地将people转换成schemardd了。这是因为spark可以隐式地将包含case class的rdd转换成schemardd。

看完上面的文章,你们对怎么实现spark schemardd隐式转换有深度的的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。