Spark SQL - count所有列中不同单词的个数



有一个包含一列的DataFrame df_titles "title":

+--------------------+
|               title|
+--------------------+
|      harry_potter_1|
|      harry_potter_2|
+--------------------+

我想知道在标题中出现的唯一术语的数量,这些术语用"_"分隔,并得到像这样的结果:

+--------------------+------+
|                term| count|
+--------------------+------+
|               harry|     2|   
|              potter|     2| 
|                   1|     1| 
|                   2|     1| 
+--------------------+------+

我正在考虑创建一个new_df与列" ter"one_answers"count",对于df_titles中的每一行,拆分字符串并插入[string, 1]到new_df。然后可以通过" ter":

来减小新的df
val test = Seq.empty[Term].toDF()
df.foreach(spark.sql("INSERT INTO test VALUES (...)"))
...

但是我被代码困住了。我该怎么做?有更好的方法吗?

您可以使用spark内置函数,如splitexplode来转换标题的数据框到术语的数据框,然后做一个简单的groupBy。你的代码应该是:

import org.apache.spark.sql.functions.{col, desc, explode, split}
df_titles
.select(explode(split(col("title"), "_")).as("term"))
.groupBy("term")
.count()
.orderBy(desc("count")) // optional, to have count in descending order

通常,当您必须在数据框架上执行某些操作时,最好首先尝试使用spark内置函数的组合,这些函数可以在spark文档

中找到。

详细信息从df_titles开始:

+--------------+
|title         |
+--------------+
|harry_potter_1|
|harry_potter_2|
+--------------+

split创建一个由_分隔的单词数组:

+-------------------+
|split(title, _, -1)|
+-------------------+
|[harry, potter, 1] |
|[harry, potter, 2] |
+-------------------+

然后,explodesplit创建的数组中为每个项目创建一行:

+------+
|col   |
+------+
|harry |
|potter|
|1     |
|harry |
|potter|
|2     |
+------+

.as("term")将列col重命名为term:

+------+
|term  |
+------+
|harry |
|potter|
|1     |
|harry |
|potter|
|2     |
+------+

.groupBy("term").count()通过term聚合计数,count().agg(count("term").as("count"))的快捷方式

+------+-----+
|term  |count|
+------+-----+
|harry |2    |
|1     |1    |
|potter|2    |
|2     |1    |
+------+-----+

最后.orderBy(desc("count"))的顺序是倒序的:

+------+-----+
|term  |count|
+------+-----+
|harry |2    |
|potter|2    |
|1     |1    |
|2     |1    |
+------+-----+

最新更新