代码之家  ›  专栏  ›  技术社区  ›  Ged

在Spark数据帧列中筛选带引号的字符串

  •  0
  • Ged  · 技术社区  · 4 年前

    我有一个DF,其中包含以下数据:

    --------+------------------------------------------+
    |recType |value                                     |
    +--------+------------------------------------------+
    |{"id": 1|{"id": 1, "user_id": 100, "price": 50}    |
    ...
    

    我可以使用筛选recType contains ,但是如何处理 === 和引号?我似乎每次都会犯一些错误。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Kombajn zbożowy    4 年前

    我知道这里的列是字符串。如果是, from_json 函数可以将它们解析为结构。

    import org.apache.spark.sql.types.{StructField, StructType, IntegerType}
    import org.apache.spark.sql.functions.from_json
    
    val recTypeSchema = StructType(Array(
        StructField("id", IntegerType, true)
    ))
    val valueSchema = StructType(Array(
        StructField("id", IntegerType, true),
        StructField("user_id", IntegerType, true),
        StructField("price", IntegerType, true)
    ))
    
    val parsedDf = df
        .withColumn("recType", from_json($"recType", recTypeSchema))
        .withColumn("value", from_json($"value", valueSchema))
    
    parsedDf.printSchema
    root
     |-- recType: struct (nullable = true)
     |    |-- id: integer (nullable = true)
     |-- value: struct (nullable = true)
     |    |-- id: integer (nullable = true)
     |    |-- user_id: integer (nullable = true)
     |    |-- price: integer (nullable = true)
    
    
    parsedDf.filter($"recType.id" === 1).show
    +-------+------------+
    |recType|       value|
    +-------+------------+
    |    {1}|{1, 100, 50}|
    +-------+------------+
    
    推荐文章