Malo
Malo

Reputation: 125

add surrounding quotes in fields while loading data into hive

I have data that looks like this:

1,Anna,London
2,Peter,Amsterdam

I want to load this data as dataframe into hive and I want to add surrounding quotes so that the data in the dataframe looks like this:

"1" "Anna" "London"
"2" "Peter" "Amsterdam"

I have set the delimiter to ",". I know that there is quote-function but it does the opposite. How can I ADD the quotes?

Upvotes: 0

Views: 155

Answers (1)

chlebek
chlebek

Reputation: 2451

you can achieve it by format_string function

scala> val df = Seq(("1","Anna","London"),("2","Peter","Amsterdam")).toDF()
df: org.apache.spark.sql.DataFrame = [_1: string, _2: string ... 1 more field]

scala> df.show()
+---+-----+---------+
| _1|   _2|       _3|
+---+-----+---------+
|  1| Anna|   London|
|  2|Peter|Amsterdam|
+---+-----+---------+


scala> val c = df.columns.map(df(_)).map((format_string("\"%s\"",_)))
c: Array[org.apache.spark.sql.Column] = Array(format_string("%s", _1), format_string("%s", _2), format_string("%s", _3))

scala> df.select(c:_*).toDF(df.columns:_*).show()
+---+-------+-----------+
| _1|     _2|         _3|
+---+-------+-----------+
|"1"| "Anna"|   "London"|
|"2"|"Peter"|"Amsterdam"|
+---+-------+-----------+

Upvotes: 1

Related Questions