SparkSQL3.0.1 读取Hive2.3.0中的数据加载DataFrame 02

在本地使用scala代码读取&创建hive数据。
本次示例中安装Spark为基于standalone集群模式,hive为高可用集群模式。
需要把hdfs-site.xml及hive-site.xml及core-site.xml文件放置于本地ide resource中
hive-site.xml配置如下:

<configuration>
    <property>  
        <name>hive.metastore.local</name>  
        <value>false</value>  
    </property>
    <property>
        <name>hive.metastore.uris</name>
        <value>thrift://node2:9083</value>
        <description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
    </property>
</configuration>

代码示例创建并读取hive表中内容:

import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}

/**
 * 本地操作Hive 读取Hive表数据加载DataFrame:
 * 注意:
 * 1).如果Hive表中的数据量大,不建议使用本地方式读取,可以用于测试。
 * 2).在本地连接Hive ,操作Hive中的数据加载DataFrame,需要配置 hive.metastore.uris 配置项。
 *
 */
object ReadHiveTableToDFLocal {
  def main(args: Array[String]): Unit = {
    //    val warehouseLocation = new File("spark-warehouse").getAbsolutePath
    val session = SparkSession.builder()
      .master("local")
      .appName("test")
      //      .config("hive.metastore.uris", "thrift://node1:9083")
      .config("hive.metastore.warehouse.dir", "/user/hive_ha/warehouse")
      .enableHiveSupport()
      .getOrCreate()

    session.sql("use spark")

    //创建 students 表
    session.sql(
      """
        | create table students(id int ,name string,age int) row format delimited fields terminated by ','
      """.stripMargin)
    //创建 score 表
    session.sql(
      """
        | create table scores(id int ,name string,score int) row format delimited fields terminated by ','
      """.stripMargin)
    //给students 表加载数据
    session.sql(
      """
        | load data local inpath 'T:/code/spark_scala/data/spark/students' into table students
      """.stripMargin)
    //给scores表加载数据
    session.sql(
      """
        | load data local inpath 'T:/code/spark_scala/data/spark/scores' into table scores
      """.stripMargin)

    //读取Hive表的数据,进行统计分析
    val result = session.sql(
      """
        | select a.id,a.name,a.age,b.score from students a join scores b on a.id = b.id where b.score >= 200
      """.stripMargin)
    result.show()

    //将结果数据保存在Hive表中
   result.write.mode(SaveMode.Overwrite).saveAsTable("goodinfos")
  }
}

问题遗留:
经测试及查阅相关资料spark.3.0.1使用spark-shell命令貌似已不能正确访问hive数据库。应使用spark-sql访问,日后研究后再做补充!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值