【问题标题】:spark convert a column of a dataframe from name to id according a hive table mapping name and idspark根据配置单元表映射名称和id将数据帧的列从名称转换为id
【发布时间】:2019-02-22 02:08:11
【问题描述】:

首先,我们在 hive 中有一个 hive 表类别:

id  |   name
1   |   history
2   |   art

...

然后我们从 mongodb 读取书籍集合来激发数据帧:

bookname    |      category
Europe      |      history book
Drawing     |      arts

这里,如果 book.category 包含 category.name 那么我需要将其转换为 id。 例如,我期望的输出是这样的数据框:

bookname    |      category
Europe      |      1
Drawing     |      2

注意!我知道我可以使用 rdd.map() 但问题是字段数实际上大于 22,但不允许使用 tuple23,所以我不能像这样使用 rdd.map:

bookDf.rdd.map(f=>{
   ....
   (field1,field2,.....filed50)//illegle
}).toDF()

还有其他方法吗?

【问题讨论】:

    标签: apache-spark dataframe hive rdd


    【解决方案1】:

    可以通过特定的连接来完成:

    val categoriesDF = List(
      (1, "history"),
      (2, "art")).toDF("id", "name")
    val booksDF = List(
      ("Europe", "history book"),
      ("Drawing", "arts")).toDF("bookname", "category")
    
    val joinCondition = $"category".contains($"name")
    val result = booksDF.join(categoriesDF, joinCondition)
    
    result.select("bookname","id").show(false)
    

    输出:

    +--------+---+
    |bookname|id |
    +--------+---+
    |Europe  |1  |
    |Drawing |2  |
    +--------+---+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多