2

I am trying to convert a column data type from long to int in spark sql using java, I have seen some of example in scala and trying out but, Its not wotking

df.withColumn("is_open",  toInt("is_open"));  

where do I need to change. thanks in advance

2
  • 1
    df.withColumn("is_open", col("is_open").cast("int")) ? Commented Jan 22, 2019 at 10:18
  • Not working, error is showing "The method col(String) is undefined for the type" @philantrovert Commented Jan 22, 2019 at 10:21

2 Answers 2

3

You can make use of the cast function.

scala> val df = spark.range(10)
df: org.apache.spark.sql.Dataset[Long] = [id: bigint]

scala> import org.apache.spark.sql.functions._
import org.apache.spark.sql.functions._

scala> df.withColumn("new_col", col("id").cast("string"))
res4: org.apache.spark.sql.DataFrame = [id: bigint, new_col: string]
Sign up to request clarification or add additional context in comments.

6 Comments

Not working in java, error is showing "The method col(String) is undefined for the type" @Constantine,
Can you check the spark documentation ? You can either use col or column. Please import it if not.
You should be able to use it after import static org.apache.spark.sql.functions.col;
yes, now error is gone by importing static function.col. But In console Info is showing CatalystSqlParser: Parsing command: int, and when we see using df.printschema(), that datatype is not converted.
This because you have to remember to update the Object: df = df.withColumn("new_col", col("id").cast("string"))
|
2
df = df.withColumn("is_open", df.col("is_open").cast("int"));

Please be aware, this cast is applying after the data is computed on previous step. If the previous step is select or something similar, it will compute into original type first, and then convert to new type on the next step. This will not solve an issue with selecting into original type.

Comments

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.