如何获取表头(schema)中的信息?

qgelzfjb  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(567)

环境:spark2.4.5
来源:id-name.json

{"1": "a", "2": "b", "3":, "c"..., "n": "z"}

我以json格式将.json文件加载到spark数据集中,其存储方式如下:

+---+---+---+---+---+
| 1 | 2 | 3 |...| n |
+---+---+---+---+---+
| a | b | c |...| z |
+---+---+---+---+---+

我希望它能产生这样的结果:

+------------+------+
|     id     | name |
+------------+------+
| 1          | a    |
| 2          | b    |
| 3          | c    |
| .          | .    |
| .          | .    |
| .          | .    |
| n          | z    |
+------------+------+

我使用spark sql的解决方案:

select stack(n, '1', `1`, '2', `2`... ,'n', `n`) as ('id', 'name') from table_name;

它不能满足我的需求,因为我不想在sql中硬编码所有的id。也许将“show columns from table\u name”与“stack()”一起使用会有所帮助?如果你能给我一些建议,我将不胜感激。

xwbd5t1u

xwbd5t1u1#

为创建所需的值 stack 动态&在需要的地方使用它。请检查下面的代码以生成相同的动态值。

scala> val js = Seq("""{"1": "a", "2": "b","3":"c","4":"d","5":"e"}""").toDS
js: org.apache.spark.sql.Dataset[String] = [value: string]

scala> val df = spark.read.json(js)
df: org.apache.spark.sql.DataFrame = [1: string, 2: string ... 3 more fields]

scala> val stack = s"""stack(${df.columns.max},${df.columns.flatMap(c => Seq(s"'${c}'",s"`${c}`")).mkString(",")}) as (id,name)"""
exprC: String = stack(5,'1',`1`,'2',`2`,'3',`3`,'4',`4`,'5',`5`) as (id,name)

scala> df.select(expr(stack)).show(false)
+---+----+
|id |name|
+---+----+
|1  |a   |
|2  |b   |
|3  |c   |
|4  |d   |
|5  |e   |
+---+----+

scala> spark.sql(s"""select ${stack} from table """).show(false)
+---+----+
|id |name|
+---+----+
|1  |a   |
|2  |b   |
|3  |c   |
|4  |d   |
|5  |e   |
+---+----+

scala>
``` `Updated Code to fetch data from json file` ```
scala> "hdfs dfs -cat /tmp/sample.json".!
{"1": "a", "2": "b","3":"c","4":"d","5":"e"}
res4: Int = 0

scala> val df = spark.read.json("/tmp/sample.json")
df: org.apache.spark.sql.DataFrame = [1: string, 2: string ... 3 more fields]

scala> val stack = s"""stack(${df.columns.max},${df.columns.flatMap(c => Seq(s"'${c}'",s"`${c}`")).mkString(",")}) as (id,name)"""
stack: String = stack(5,'1',`1`,'2',`2`,'3',`3`,'4',`4`,'5',`5`) as (id,name)

scala> df.select(expr(stack)).show(false)
+---+----+
|id |name|
+---+----+
|1  |a   |
|2  |b   |
|3  |c   |
|4  |d   |
|5  |e   |
+---+----+

scala> df.createTempView("table")

scala> spark.sql(s"""select ${stack} from table """).show(false)
+---+----+
|id |name|
+---+----+
|1  |a   |
|2  |b   |
|3  |c   |
|4  |d   |
|5  |e   |
+---+----+

相关问题