【问题标题】:Access hive table with json serde via spark sql通过 spark sql 使用 json serde 访问 hive 表
【发布时间】:2020-09-05 04:26:59
【问题描述】:

我是 SPARK 世界的新手。以何种方式,可以通过 spark sql 读取带有 JSON serde 的 hive 表。任何示例代码或文档都可以使用。

【问题讨论】:

  • 如果您使用spark 2.0+,请在创建火花会话时尝试设置spark = SparkSession.builder.enableHiveSupport().getOrCreate()

标签: json apache-spark hive hive-serde


【解决方案1】:
import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession

object ReadJson {
  val spark = SparkSession // Building Spark object
    .builder()
    .appName("ReadJson")
    .master("local[*]")
    .config("spark.sql.shuffle.partitions","4") //Change to a more reasonable default number of partitions for our data
    .config("spark.app.id","RareJson") // To silence Metrics warning
    .getOrCreate()

  val sc = spark.sparkContext // Get the spark context

  val sqlContext = spark.sqlContext  // Get the spark Sql Context

  val input = "hdfs://user/..../..../..../file.json" //hdfs path to the file or directory

  def main(args: Array[String]): Unit = {

    Logger.getRootLogger.setLevel(Level.ERROR)  // application logs

    try {

      val jsonDf = sqlContext
        .read    
        .json(input) // reading the Json file and getting a DataFrame

      jsonDf.show(truncate = false) // showing some data in the console

      jsonDf.createOrReplaceTempView("my_table") // to work with SQL first we create a temporal view

      sqlContext.sql("""SELECT * FROM my_table""").show() //simple query

      // To have the opportunity to view the web console of Spark: http://localhost:4041/
      println("Type whatever to the console to exit......")
      scala.io.StdIn.readLine()
    } finally {
      sc.stop()
      println("SparkContext stopped")
      spark.stop()
      println("SparkSession stopped")
    }
  }
}

Spark 编程指南

http://spark.apache.org/docs/2.3.0/sql-programming-guide.html#overview

【讨论】:

  • 其实我不是直接从 JSON 文件中读取,而是数据以 JSON Serde 格式存储在 HIVE 表中,我不知道如何从那里读取数据。
  • 您可以尝试这种方法,我想数据以 json 格式存储,因此您可以读取文件,使用 spark 进行更改或聚合,并保存覆盖目录的数据。 Hive 将能够读取更改。其他方法是启用 HiveSupport 并建立 Hive 仓库目录并直接读取表。您使用的是什么版本的 Spark? Yoy可以点击这个链接:spark.apache.org/docs/2.3.0/….
猜你喜欢
  • 2019-09-21
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2016-02-28
  • 1970-01-01
  • 2017-12-23
  • 2015-01-22
相关资源
最近更新 更多