在 Spark 中使用 groupBy 并返回到 DataFrame [英] Using groupBy in Spark and getting back to a DataFrame

查看:76
本文介绍了在 Spark 中使用 groupBy 并返回到 DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用 Scala 处理 Spark 中的数据帧时遇到了困难.如果我有一个数据框想要提取一列唯一条目,当我使用 groupBy 时,我不会得到一个数据框.

I have a difficulty when working with data frames in spark with Scala. If I have a data frame that I want to extract a column of unique entries, when I use groupBy I don't get a data frame back.

例如,我有一个名为 logs 的 DataFrame,其格式如下:

For example, I have a DataFrame called logs that has the following form:

machine_id  | event     | other_stuff
 34131231   | thing     |   stuff
 83423984   | notathing | notstuff
 34131231   | thing    | morestuff

并且我想要唯一的机器 ID,其中事件是存储在新的 DataFrame 中的东西,以允许我进行某种过滤.使用

and I would like the unique machine ids where event is thing stored in a new DataFrame to allow me to do some filtering of some kind. Using

val machineId = logs
  .where($"event" === "thing")
  .select("machine_id")
  .groupBy("machine_id")

我得到了一组分组数据,使用起来很麻烦(或者我不知道如何正确使用这种对象).获得了这个唯一机器 ID 的列表后,我想用它来过滤另一个 DataFrame 以提取单个机器 ID 的所有事件.

I get a val of Grouped Data back which is a pain in the butt to use (or I don't know how to use this kind of object properly). Having got this list of unique machine id's, I then want to use this in filtering another DataFrame to extract all events for individual machine ids.

我可以看到我想要经常做这种事情,基本工作流程是:

I can see I'll want to do this kind of thing fairly regularly and the basic workflow is:

  1. 从日志表中提取唯一 ID.
  2. 使用唯一 ID 提取特定 ID 的所有事件.
  3. 对已提取的数据进行某种分析.

这是前两个步骤,我希望在这里得到一些指导.

It's the first two steps I would appreciate some guidance with here.

我很欣赏这个例子有点做作,但希望它能解释我的问题.可能是我对 GroupedData 对象的了解不够,或者(正如我希望的那样)我在数据框中遗漏了一些使这变得容易的东西.我使用的是基于 Scala 2.10.4 的 spark 1.5.

I appreciate this example is kind of contrived but hopefully it explains what my issue is. It may be I don't know enough about GroupedData objects or (as I'm hoping) I'm missing something in data frames that makes this easy. I'm using spark 1.5 built on Scala 2.10.4.

谢谢

推荐答案

只使用 distinct 而不是 groupBy:

val machineId = logs.where($"event"==="thing").select("machine_id").distinct

这将等同于 SQL:

SELECT DISTINCT machine_id FROM logs WHERE event = 'thing'

GroupedData 不打算直接使用.它提供了多种方法,其中agg是最通用的,可用于应用不同的聚合函数并将其转换回DataFrame.在 SQL 方面,您在 wheregroupBy 之后拥有的内容相当于这样的东西

GroupedData is not intended to be used directly. It provides a number of methods, where agg is the most general, which can be used to apply different aggregate functions and convert it back to DataFrame. In terms of SQL what you have after where and groupBy is equivalent to something like this

SELECT machine_id, ... FROM logs WHERE event = 'thing' GROUP BY machine_id

其中 ... 必须由 agg 或等效方法提供.

where ... has to be provided by agg or equivalent method.

这篇关于在 Spark 中使用 groupBy 并返回到 DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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