Сохранение таблицы в улье с Java Spark SQL из массива JSON - PullRequest
0 голосов
/ 20 сентября 2018
    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, а в этом единственном столбце находится контекст <1010 *.

1 Ответ

0 голосов
/ 20 сентября 2018

Немного запутанно, но я нашел, что это работает:

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]"
...