【问题标题】:Save table in hive with java spark sql from json array使用来自json数组的java spark sql将表保存在hive中
【发布时间】:2018-09-19 21:49:56
【问题描述】:
    Dataset<Row> ds = spark.read().option("multiLine", true).option("mode", "PERMISSIVE").json("/user/administrador/prueba_diario.txt").toDF();

    ds.printSchema();

    Dataset<Row> ds2 = ds.select("articles").toDF();

    ds2.printSchema();
    spark.sql("drop table if exists table1"); 
    ds2.write().saveAsTable("table1");

我有这个json格式

root
 |-- articles: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- author: string (nullable = true)
 |    |    |-- content: string (nullable = true)
 |    |    |-- description: string (nullable = true)
 |    |    |-- publishedAt: string (nullable = true)
 |    |    |-- source: struct (nullable = true)
 |    |    |    |-- id: string (nullable = true)
 |    |    |    |-- name: string (nullable = true)
 |    |    |-- title: string (nullable = true)
 |    |    |-- url: string (nullable = true)
 |    |    |-- urlToImage: string (nullable = true)
 |-- status: string (nullable = true)
 |-- totalResults: long (nullable = true)

我想将数组文章保存为具有数组格式的配置单元表

我想要的配置单元表示例:

author (string)
content (string)
description (string)
publishedat (string)
source (struct<id:string,name:string>)
title (string)
url (string)
urltoimage (string)

问题是只用一列名为 article 保存表,而竞争就在这一列中

【问题讨论】:

    标签: java json hadoop hive apache-spark-sql


    【解决方案1】:

    有点复杂,但我发现这个可以工作:

    import org.apache.spark.sql.functions._
    ds.select(explode(col("articles")).as("exploded")).select("exploded.*").toDF()
    

    我测试过

    {
      "articles": [
        {
          "author": "J.K. Rowling",
          "title": "Harry Potter and the goblet of fire"
        },
        {
          "author": "George Orwell",
          "title": "1984"
        }
      ]
    }
    

    它返回了(在将它收集到一个数组之后)

    result = {Arrays$ArrayList@13423}  size = 2
     0 = {GenericRowWithSchema@13425} "[J.K. Rowling,Harry Potter and the goblet of fire]"
     1 = {GenericRowWithSchema@13426} "[George Orwell,1984]"
    

    【讨论】:

    • 我做到了,我在线程“main”org.apache.spark.sql.AnalysisException 中遇到了这个错误异常:只能星号扩展结构数据类型。属性:ArrayBuffer(articles);在 org.apache.spark.sql.catalyst.analysis.UnresolvedStar.expand(unresolved.scala:27​​5)
    • 对不起,我看错了你的架构,它是一个数组而不是一个结构。我会自己尝试一下。
    • @Bar 已修复,现在应该做你想做的事
    • 是的,但是它将数据保存在单个列中。它应该在 hive 中生成列,因为结构中有列。
    • 非常感谢您的帮助,您给了我一个很好的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2015-09-29
    • 2019-09-21
    • 1970-01-01
    • 2016-12-25
    • 2020-07-12
    相关资源
    最近更新 更多