0

我正在用 Java 编写 Spark 应用程序,我想知道如何从文字值创建 DataFrame 和/或 JavaRDD。

例如,我有 3 个整数,比如说(784512, 35, 40)对应于 fields / columns (id, m_count, f_count)

4

1 回答 1

2

您想SparkContext.parallelize(...)创建一个 JavaRDD 并创建一个数据框SQLContext.createDataFrame(...)

JavaRDD rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4));

如果您在创建具有三个值的对象的并行列表之后,那么您需要:

  @Test                                                                                                 
  public void test() {                                                                   
      JavaSparkContext sc =  ...                                                    
      SQLContext sqlContext =  new SQLContext(sc);                                                      

      JavaRDD<Counter> counters = sc.parallelize(Arrays.asList(new Counter(784512, 35, 40)));           
      DataFrame countersDF = sqlContext.createDataFrame(counters, Counter.class);                       

      System.out.println(counters.collect());                                                           
      System.out.println(countersDF.collectAsList());                                                           
  }                                                                                                     



  public static class Counter implements Serializable{                                                         
      private final int id;                                                                             
      private final int m_count;                                                                        
      private final int f_count;                                                                        

      Counter(int id, int m_count, int f_count) {                                                       
          this.id = id;                                                                                 
          this.m_count = m_count;                                                                       
          this.f_count = f_count;                                                                       
      }                                                                                                 

      public String toString() {                                                                        
          return id + " " + m_count + " "  + f_count;                                                   
      }    
      // getters                                                                                          
  }                                                                                                     
于 2015-11-16T10:36:01.350 回答