使用Java API创建一个简单的1行Spark DataFrame [英] Creating a simple 1-row Spark DataFrame with Java API

查看:141
本文介绍了使用Java API创建一个简单的1行Spark DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我可以从内存中的字符串创建单行DataFrame,如下所示:

In Scala, I can create a single-row DataFrame from an in-memory string like so:

val stringAsList = List("buzz")
val df = sqlContext.sparkContext.parallelize(jsonValues).toDF("fizz")
df.show()

df.show()运行时,它输出:

+-----+
| fizz|
+-----+
| buzz|
+-----+

现在我正在尝试做这来自Java类。显然 JavaRDD s没有 toDF(String)方法。我试过了:

Now I'm trying to do this from inside a Java class. Apparently JavaRDDs don't have a toDF(String) method. I've tried:

List<String> stringAsList = new ArrayList<String>();
stringAsList.add("buzz");
SQLContext sqlContext = new SQLContext(sparkContext);
DataFrame df = sqlContext.createDataFrame(sparkContext
    .parallelize(stringAsList), StringType);
df.show();

......但似乎仍然很短。现在当 df.show(); 执行时,我得到:

...but still seem to be coming up short. Now when df.show(); executes, I get:

++
||
++
||
++

(空DF。)所以我问:使用 Java API ,如何将内存中的字符串读入其中只有1行和1列的DataFrame,并指定该列的名称?(以便 df.show()与上面的Scala相同)?

(An empty DF.) So I ask: Using the Java API, how do I read an in-memory string into a DataFrame that has only 1 row and 1 column in it, and also specify the name of that column? (So that the df.show() is identical to the Scala one above)?

推荐答案

你可以通过创建List到Rdd而不是创建包含列名的Schema来实现这一点。

You can achieve this by creating List to Rdd and than create Schema which will contain column name.

可能还有其他方法,它只是其中之一。

There might be other ways as well, it's just one of them.

List<String> stringAsList = new ArrayList<String>();
        stringAsList.add("buzz");

JavaRDD<Row> rowRDD = sparkContext.parallelize(stringAsList).map((String row) -> {
                return RowFactory.create(row);
            });

StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("fizz", DataTypes.StringType, false) });

DataFrame df = sqlContext.createDataFrame(rowRDD, schema).toDF();
df.show();

//+----+
|fizz|
+----+
|buzz|

这篇关于使用Java API创建一个简单的1行Spark DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆