PySpark左外连接后song_id和artist_id全为None求助
PySpark左连接后关联字段全为None问题排查方案
1. 检查关联字段的数据类型与值匹配度
- 先确认
dfEvents.artist和dfSongs.artist_name、dfEvents.song和dfSongs.title的数据类型是否一致,若类型不匹配(比如一个是字符串、一个是数组),直接关联会失败:# 打印字段结构检查类型 dfEvents.select("artist", "song").printSchema() dfSongs.select("artist_name", "title").printSchema() - 检查字段值的大小写、空格、特殊字符差异,比如"Coldplay"和"coldplay"、"Hello World"(多空格)这类细微差异都会导致匹配失败:
# 查看去重后的样本值对比 dfEvents.select("artist", "song").distinct().show(10, truncate=False) dfSongs.select("artist_name", "title").distinct().show(10, truncate=False) # 尝试清洗字段后再关联 from pyspark.sql.functions import trim, lower dfEvents_clean = dfEvents.withColumn("artist_clean", trim(lower("artist"))) \ .withColumn("song_clean", trim(lower("song"))) dfSongs_clean = dfSongs.withColumn("artist_name_clean", trim(lower("artist_name"))) \ .withColumn("title_clean", trim(lower("title")))
2. 确认关联条件的逻辑正确性
- 左连接需同时满足两个字段的匹配条件,避免误将
&写成|导致逻辑错误:
错误写法:
正确写法:dfJoined = dfEvents.join(dfSongs, (dfEvents.artist == dfSongs.artist_name) | (dfEvents.song == dfSongs.title), "left_outer")dfJoined = dfEvents.join(dfSongs, (dfEvents.artist == dfSongs.artist_name) & (dfEvents.song == dfSongs.title), "left_outer") - 使用别名时确保字段引用无歧义:
df_e = dfEvents.alias("e") df_s = dfSongs.alias("s") dfJoined = df_e.join(df_s, (df_e.artist == df_s.artist_name) & (df_e.song == df_s.title), "left_outer")
3. 验证是否存在可匹配的数据
- 先执行内连接统计匹配记录数,确认两个表是否真的有符合条件的关联数据:
如果match_count = dfEvents.join(dfSongs, (dfEvents.artist == dfSongs.artist_name) & (dfEvents.song == dfSongs.title), "inner").count() print(f"可匹配的记录总数:{match_count}")match_count为0,说明两个表确实没有匹配数据,需要检查数据源或调整匹配规则。
4. 排查空值干扰
- 检查关联字段本身的空值情况,空值无法与任何值匹配:
可根据业务需求,在关联前过滤空值,或调整逻辑处理空值场景。# 统计关联字段的空值数量 print(f"dfEvents.artist空值数:{dfEvents.filter(dfEvents.artist.isNull()).count()}") print(f"dfEvents.song空值数:{dfEvents.filter(dfEvents.song.isNull()).count()}") print(f"dfSongs.artist_name空值数:{dfSongs.filter(dfSongs.artist_name.isNull()).count()}") print(f"dfSongs.title空值数:{dfSongs.filter(dfSongs.title.isNull()).count()}")
内容的提问来源于stack exchange,提问作者SRJ
相关产品推荐
相关产品推荐

