我有一个与apache 电光和PostgreSQL的jdbc连接,我想将一些数据插入到我的数据库中.当我使用append
模式时,我需要 for each DataFrame.Row
指定id
.电光有没有办法创建主键?
我有一个与apache 电光和PostgreSQL的jdbc连接,我想将一些数据插入到我的数据库中.当我使用append
模式时,我需要 for each DataFrame.Row
指定id
.电光有没有办法创建主键?
Scala:
如果您只需要唯一的数字,您可以使用zipWithUniqueId
并重新创建DataFrame.首先是一些导入和虚拟数据:
import sqlContext.implicits._
import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StructType, StructField, LongType}
val df = sc.parallelize(Seq(
("a", -1.0), ("b", -2.0), ("c", -3.0))).toDF("foo", "bar")
提取架构以供进一步使用:
val schema = df.schema
添加ID字段:
val rows = df.rdd.zipWithUniqueId.map{
case (r: Row, id: Long) => Row.fromSeq(id +: r.toSeq)}
创建数据帧:
val dfWithPK = sqlContext.createDataFrame(
rows, StructType(StructField("id", LongType, false) +: schema.fields))
同样的事情在Python年里也是如此:
from pyspark.sql import Row
from pyspark.sql.types import StructField, StructType, LongType
row = Row("foo", "bar")
row_with_index = Row(*["id"] + df.columns)
df = sc.parallelize([row("a", -1.0), row("b", -2.0), row("c", -3.0)]).toDF()
def make_row(columns):
def _make_row(row, uid):
row_dict = row.asDict()
return row_with_index(*[uid] + [row_dict.get(c) for c in columns])
return _make_row
f = make_row(df.columns)
df_with_pk = (df.rdd
.zipWithUniqueId()
.map(lambda x: f(*x))
.toDF(StructType([StructField("id", LongType(), False)] + df.schema.fields)))
如果你更喜欢连续数字,你可以用zipWithIndex
代替zipWithUniqueId
,但这要贵一点.
Directly with 100 API:
(universal Scala, Python, Java, R with pretty much the same syntax)个
以前我错过了monotonicallyIncreasingId
函数,只要不需要连续的数字,它就应该可以很好地工作:
import org.apache.spark.sql.functions.monotonicallyIncreasingId
df.withColumn("id", monotonicallyIncreasingId).show()
// +---+----+-----------+
// |foo| bar| id|
// +---+----+-----------+
// | a|-1.0|17179869184|
// | b|-2.0|42949672960|
// | c|-3.0|60129542144|
// +---+----+-----------+
而有用的monotonicallyIncreasingId
是非确定性的.当后续操作包含筛选器时,不仅ID可能因执行而不同,而且没有其他技巧,也不能用来标识行.
Note:
也可以使用rowNumber
窗口函数:
from pyspark.sql.window import Window
from pyspark.sql.functions import rowNumber
w = Window().orderBy()
df.withColumn("id", rowNumber().over(w)).show()
不幸的是:
警告窗口:没有为窗口操作定义分区!将所有数据移动到单个分区可能会导致严重的性能下降.
因此,除非您有一种对数据进行分区并确保唯一性的自然方法,否则此时不会特别有用.