从文字值创建 DataFrame 和 JavaRDD

Create a DataFrame and JavaRDD from literal values

我正在 Java 中编写一个 Spark 应用程序,我想知道如何从文字值创建 DataFrame and/or JavaRDD。

例如我有 3 个整数,比如 (784512, 35, 40) 对应字段/列 (id, m_count, f_count)

您希望SparkContext.parallelize(...) to create a JavaRDD and 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                                                                                          
  }