1

Using Apache Spark in Java, I have:

root
 |-- datasetid: string (nullable = true)
 |-- fields: struct (nullable = true)
...
 |    |-- latlon: array (nullable = true)
 |    |    |-- element: double (containsNull = true)

This is based on this JSON fragment:

"fields":{
  "latlon":[
    35.9543748,
    -78.9944911
  ],

I was trying to extract the data to a column using:

df = df.withColumn("lat", df.col("fields.latlon[0]"));
df = df.withColumn("lon", df.col("fields.latlon[1]"));

(I hope you appreciate the neatness of the syntax). However, I must admit it does not really work:

No such struct field latlon[1] in 

I tried a few other things without much luck...

1 Answer 1

1

Use code

df.withColumn("lat", $"fields.latlon".getItem(0))
  .withColumn("lon", $"fields.latlon".getItem(1))

Use sql

df.registerTempTable("geo")
latlon = sqlContext.sql("select fields.latlon[0] as lat, fields.latlon[1] as lon from geo")
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome @Rockie! I just changed the notation to be more Java and less Scala using the static method col(). Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.