【问题标题】:Constructing Java hashmap from Spark dataframe从 Spark 数据帧构造 Java hashmap
【发布时间】:2020-11-07 01:57:28
【问题描述】:

我在我的项目中使用 spark-sql-2.4.1v 和 Java 8。

我需要从给定的数据帧构造一个循环哈希图,如下所示:

List ll = Arrays.asList(
      ("aaaa", 11),
      ("aaa", 12),
      ("aa", 13),
      ("a", 14)
    )

Dataset<Row> codeValudeDf = ll.toDF( "code", "value")

鉴于上述数据框,我需要创建一个哈希图

Map<String, String> lookUpHm = new Hashmap<>();

lookUpHm  => aaaa->11  , aaa->12 , aa->13, a->14

用Java怎么做?

【问题讨论】:

    标签: java dataframe apache-spark apache-spark-sql


    【解决方案1】:

    试试这个-

     List<Row> rows = Arrays.asList(
                    RowFactory.create("aaaa", 11),
                    RowFactory.create("aaa", 12),
                    RowFactory.create("aa", 13),
                    RowFactory.create("a", 14)
            );
    
            Dataset<Row> codeValudeDf = spark.createDataFrame(rows, new StructType()
                    .add("code", DataTypes.StringType, true, Metadata.empty())
                    .add("value", DataTypes.IntegerType, true, Metadata.empty()));
            Map<String, Integer> map = new HashMap<>();
            codeValudeDf.collectAsList().forEach(row -> map.put(row.getString(0), row.getInt(1)));
    
            System.out.println(map.entrySet().stream().map(e -> e.getKey() +"->"+ e.getValue())
                    .collect(Collectors.joining(", ", "[ ", " ]")));
            // [ aaa->12, aa->13, a->14, aaaa->11 ]
    

    【讨论】:

      【解决方案2】:

      使用 withColumn 简单地添加一个类型为 map 的新列,然后对您的数据框进行收集。

      codeValudeDf.withColumn("some_map",
      map(col("code"), col("value"))).select("some_map").distinct().collect()
      

      【讨论】:

      • getting error org.apache.spark.sql.AnalysisException: Can not have map type columns in DataFrame which calls set operations(intersect, except, etc.), but the type of column some_map is map;;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      相关资源
      最近更新 更多