Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

How to retrieve a value from struct in Spark Java?

My Dataset ds has the following schema:

root
 |-- id: string (nullable = true)
 |-- type: string (nullable = true)
 |-- item: struct (nullable = true)
 |    |-- item: string (nullable = true)

Sample:

{"id":"1","type": "aaa", "item": {"item":"11"}}
{"id":"2","type": "bbb", "item" : {"item":"12"}}

How can I retrieve item from struct to get this result?

id   type    item
1    aaa     11
2    bbb     12

This is what I tried without success:

ds.select("id", "type", "item.0");

Please notice that I use Java. Do not post answers in Scala or Python unless they are identical for Java.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Suppose you have your sample file:

{"id":"1","type": "aaa", "item": {"item":"11"}}
{"id":"2","type": "bbb", "item" : {"item":"12"}}

You can test the following Java code:

public class SparkJavaTest {
    public static SparkSession spark = SparkSession
            .builder()
            .appName("JavaSparkTest")
            .master("local")
            .getOrCreate();


    public static void main(String[] args) {

    Dataset<Row> ds1 = spark.read().json("sample.json");

ds1.printSchema();

ds1.select("id", "type", "item.item").show(false);

The result would be:

root
 |-- id: string (nullable = true)
 |-- item: struct (nullable = true)
 |    |-- item: string (nullable = true)
 |-- type: string (nullable = true)


+---+----+----+
|id |type|item|
+---+----+----+
|1  |aaa |11  |
|2  |bbb |12  |
+---+----+----+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...