เพิ่มฟิลด์ที่สร้างอัตโนมัติให้กับดาต้าเฟรม

ฉันมี dataframe นี้ซึ่งมีค่าอยู่

val cabArticleLocal = spark.load("jdbc", Map("url" -> url, "dbtable" -> "cabarticle"))
cabArticleLocal.show
root
 |-- is_enabled: boolean (nullable = true)
 |-- cab_article: long (nullable = true)
 |-- article_id: long (nullable = true)

 +----------+-----------+----------+
 |is_enabled|cab_article|article_id|
 +----------+-----------+----------+
 +----------+-----------+----------+

ที่จะถูกแทรกลงในฐานข้อมูล PostgreSQL ด้วยโครงสร้างนี้

id 
is_enabled
cab_article
article_id 

ฉันจะสร้างรหัสฟิลด์ลงใน dataframe ให้เป็นรหัสที่สร้างอัตโนมัติซึ่งแทรกลงใน dataframe ที่มีอยู่ได้อย่างไร ขอบคุณ

+----------+-----------+----------+---+
|is_enabled|cab_article|article_id| id|
+----------+-----------+----------+---+
+----------+-----------+----------+---+

person maher    schedule 24.10.2017    source แหล่งที่มา


คำตอบ (1)


คุณสามารถใช้ฟังก์ชัน monotonically_increasing_id ได้ดังต่อไปนี้

import org.apache.spark.sql.functions._
cabArticleLocal.withColumn("id", monotonically_increasing_id())

หรือคุณสามารถใช้ฟังก์ชัน row_number บนฟังก์ชัน Window ได้

import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions.Window
cabArticleLocal.withColumn("id", row_number().over(Window.orderBy("article_id")))

หรือคุณสามารถใช้ภาษาแบบสอบถามเป็น

cabArticleLocal.createOrReplaceTempView("tempTable")
sqlContext.sql("select row_number() over (order by article_id) as id,is_enabled,cab_article,article_id from tempTable")
person Ramesh Maharjan    schedule 24.10.2017