开发者社区> 问答> 正文

PYSPARK:使用另一个表中的两列之一加入表列

我的问题如下:

Table 1
ID1 ID2
1 2
3 4

Table 2
C1 VALUE
1 London
4 Texas

Table3
C3 VALUE
2 Paris
3 Arizona
表1具有主要和次要ID。我需要根据table1的Ids映射创建一个最终输出,它是Table2和Table3中值的聚合。

即,如果table2或table3中的值映射到任一ID,则应将其聚合为一个。

i.e my final output should look like:

ID Aggregated
1 [2, London, Paris] // since Paris is mapped to 2 which is turn is mapped to 1
3 [4, Texas, Arizona] // Texas is mapped to 4 which in turn is mapped to 3
任何建议如何在pyspark实现这一目标。

我不确定加入这些表是否有助于解决这个问题。

我当时认为PairedRDD可能会帮助我,但我无法找到合适的解决方案。

展开
收起
社区小助手 2019-01-02 15:16:20 2146 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    以下是一种非常直接的方法:

    spark.sql(
    """
    select 1 as id1,2 as id2
    union
    select 3 as id1,4 as id2
    """).createOrReplaceTempView("table1")

    spark.sql(
    """
    select 1 as c1, 'london' as city
    union
    select 4 as c1, 'texas' as city
    """).createOrReplaceTempView("table2")

    spark.sql(
    """
    select 2 as c1, 'paris' as city
    union
    select 3 as c1, 'arizona' as city
    """).createOrReplaceTempView("table3")

    spark.table("table1").show()
    spark.table("table2").show()
    spark.table("table3").show()

    for simplicity, union table2 and table 3

    spark.sql(""" select from table2 union all select from table3 """).createOrReplaceTempView("city_mappings")
    spark.table("city_mappings").show()

    now join to the ids:

    spark.sql("""
    select id1, id2, city from table1
    join city_mappings on c1 = id1 or c1 = id2
    """).createOrReplaceTempView("id_to_city")

    2019-07-17 23:24:25
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载