我在hive表中的pyspark中创建了两个数据框,如下所示:
data1 = spark.sql("""
SELECT ID, MODEL_NUMBER, MODEL_YEAR ,COUNTRY_CODE
from MODEL_TABLE1 where COUNTRY_CODE in ('IND','CHN','USA','RUS','AUS')
""");
每个国家/地区都有数百万个字母数字格式的唯一ID。
data2 = spark.sql("""
SELECT ID,MODEL_NUMBER, MODEL_YEAR, COUNTRY_CODE
from MODEL_TABLE2 where COUNTRY_CODE in ('IND','CHN')
""");
我想使用ID列上的pyspark将这两个数据框都加入。
我们如何重新划分数据,以使其在各个分区之间均匀分布。
我可以在下面使用它来修复我的数据吗?
newdf1 = data2.repartition(100, "ID")
newdf2 = data2.repartition(100, "ID")
什么是最好的分区方法,以便更快地进行连接?
答案 0 :(得分:2)
据我所知,提供ID列的方法repartition
是正确的。考虑以下内容作为使用spark_partition_id()
来获取相应分区ID的概念证明:
import pandas as pd
import numpy as np
from pyspark.sql.functions import spark_partition_id
def create_dummy_data():
data = np.vstack([np.random.randint(0, 5, size=10),
np.random.random(10)])
df = pd.DataFrame(data.T, columns=["id", "values"])
return spark.createDataFrame(df)
def show_partition_id(df):
"""Helper function to show partition."""
return df.select(*df.columns, spark_partition_id().alias("pid")).show()
df1 = create_dummy_data()
df2 = create_dummy_data()
show_partition_id(df1)
+---+-------------------+---+
| id| values|pid|
+---+-------------------+---+
|1.0| 0.6051170383675885| 0|
|3.0| 0.4613520717857513| 0|
|0.0| 0.797734780966592| 1|
|2.0|0.35594664760134587| 1|
|2.0|0.08223203758144915| 2|
|0.0| 0.3112880092048709| 2|
|4.0| 0.2689639324292137| 3|
|1.0| 0.6466782159542134| 3|
|0.0| 0.8340472796153436| 3|
|4.0| 0.8054752411745659| 3|
+---+-------------------+---+
show_partition_id(df2)
+---+-------------------+---+
| id| values|pid|
+---+-------------------+---+
|4.0| 0.8950517294190533| 0|
|3.0| 0.4084717827425539| 0|
|3.0| 0.798146627431009| 1|
|4.0| 0.8039931522181247| 1|
|3.0| 0.732125135531736| 2|
|0.0| 0.536328329270619| 2|
|1.0|0.25952064363007576| 3|
|2.0| 0.1958334111199559| 3|
|0.0| 0.728098753644471| 3|
|0.0| 0.9825387111807906| 3|
+---+-------------------+---+
show_partition_id(df1.repartition(2, "id"))
+---+-------------------+---+
| id| values|pid|
+---+-------------------+---+
|1.0| 0.6051170383675885| 0|
|3.0| 0.4613520717857513| 0|
|4.0| 0.2689639324292137| 0|
|1.0| 0.6466782159542134| 0|
|4.0| 0.8054752411745659| 0|
|0.0| 0.797734780966592| 1|
|2.0|0.35594664760134587| 1|
|2.0|0.08223203758144915| 1|
|0.0| 0.3112880092048709| 1|
|0.0| 0.8340472796153436| 1|
+---+-------------------+---+
show_partition_id(df2.repartition(2, "id"))
+---+-------------------+---+
| id| values|pid|
+---+-------------------+---+
|4.0| 0.8950517294190533| 0|
|3.0| 0.4084717827425539| 0|
|3.0| 0.798146627431009| 0|
|4.0| 0.8039931522181247| 0|
|3.0| 0.732125135531736| 0|
|1.0|0.25952064363007576| 0|
|0.0| 0.536328329270619| 1|
|2.0| 0.1958334111199559| 1|
|0.0| 0.728098753644471| 1|
|0.0| 0.9825387111807906| 1|
+---+-------------------+---+
重新分区后,id 0和2位于同一分区上,其余的位于另一个分区上。