-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdata_frame.rb
More file actions
269 lines (236 loc) · 6.6 KB
/
data_frame.rb
File metadata and controls
269 lines (236 loc) · 6.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
module Spark
module SQL
##
# Spark::SQL::DataFrame
#
# All example are base on people.json
#
class DataFrame
attr_reader :jdf, :sql_context
def initialize(jdf, sql_context)
@jdf = jdf
@sql_context = sql_context
end
# Returns the column as a {Column}.
#
# == Examples:
# df.select(df['age']).collect
# # => [#<Row {"age"=>2}>, #<Row {"age"=>5}>]
#
# df[ ["name", "age"] ].collect
# # => [#<Row {"name"=>"Alice", "age"=>2}>, #<Row {"name"=>"Bob", "age"=>5}>]
#
# df[ df.age > 3 ].collect
# # => [#<Row {"age"=>5, "name"=>"Bob"}>]
#
# df[df[0] > 3].collect
# # => [#<Row {"age"=>5, "name"=>"Bob"}>]
#
def [](item)
case item
when String
jcolumn = jdf.apply(item)
Column.new(jcolumn)
when Array
select(*items)
when Numeric
jcolumn = jdf.apply(columns[item])
Column.new(jcolumn)
when Column
where(item)
else
raise ArgumentError, "Unsupported type: #{item.class}"
end
end
# Returns all column names as a Array.
#
# == Example:
# df.columns
# # => ['age', 'name']
#
def columns
schema.fields.map(&:name)
end
# Returns the schema of this {DataFrame} as a {StructType}.
def schema
return @schema if @schema
begin
@schema = DataType.parse(JSON.parse(jdf.schema.json))
rescue => e
raise Spark::ParseError, 'Unable to parse datatype from schema'
end
end
def show_string(n=20, truncate=true)
jdf.showString(n, truncate)
end
# Prints the first n rows to the console.
#
# == Parameters:
# n:: Number of rows to show.
# truncate:: Whether truncate long strings and align cells right.
#
def show(n=20, truncate=true)
puts show_string(n, truncate)
end
# Prints out the schema in the tree format.
#
# == Example:
# df.print_schema
# # root
# # |-- age: integer (nullable = true)
# # |-- name: string (nullable = true)
#
def print_schema
puts jdf.schema.treeString
end
def explain(extended=false)
if extended
jdf.queryExecution.toString
else
jdf.queryExecution.executedPlan.toString
end
end
# Prints the (logical and physical) plans to the console for debugging purpose.
#
# == Example:
# df.print_explain
# # Scan PhysicalRDD[age#0,name#1]
#
# df.print_explain(true)
# # == Parsed Logical Plan ==
# # ...
# # == Analyzed Logical Plan ==
# # ...
# # == Optimized Logical Plan ==
# # ...
# # == Physical Plan ==
# # ...
#
def print_explain(extended=false)
puts explain(extended)
end
# Returns all column names and their data types as a list.
#
# == Example:
# df.dtypes
# # => [('age', 'int'), ('name', 'string')]
#
def dtypes
schema.fields.map do |field|
[field.name, field.data_type.simple_string]
end
end
def inspect
types = dtypes.map do |(name, type)|
"#{name}: #{type}"
end
"#<DataFrame(#{types.join(', ')})>"
end
# Get column by name
def method_missing(method, *args, &block)
name = method.to_s
if columns.include?(name)
self[name]
else
super
end
end
# =============================================================================
# Collect
# Returns all the records as a list of {Row}.
#
# == Example:
# df.collect
# # => [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
#
def collect
Spark.jb.call(jdf, 'collect')
end
def collect_as_hash
result = collect
result.map!(&:to_h)
result
end
def values
result = collect
result.map! do |item|
item.to_h.values
end
result
end
# Returns the number of rows in this {DataFrame}.
def count
jdf.count.to_i
end
# Returns the first num rows as an Array of {Row}.
def take(num)
limit(num).collect
end
# =============================================================================
# Queries
# Projects a set of expressions and returns a new {DataFrame}
#
# == Parameters:
# *cols::
# List of column names (string) or expressions {Column}.
# If one of the column names is '*', that column is expanded to include all columns
# in the current DataFrame.
#
# == Example:
# df.select('*').collect
# # => [#<Row {"age"=>2, "name"=>"Alice"}>, #<Row {"age"=>5, "name"=>"Bob"}>]
#
# df.select('name', 'age').collect
# # => [#<Row {"name"=>"Alice", "age"=>2}>, #<Row {"name"=>"Bob", "age"=>5}>]
#
# df.select(df.name, (df.age + 10).alias('age')).collect
# # => [#<Row {"name"=>"Alice", "age"=>12}>, #<Row {"name"=>"Bob", "age"=>15}>]
#
def select(*cols)
jcols = cols.map do |col|
Column.to_java(col)
end
new_jdf = jdf.select(jcols)
DataFrame.new(new_jdf, sql_context)
end
# Filters rows using the given condition.
#
# == Examples:
# df.filter(df.age > 3).collect
# # => [#<Row {"age"=>5, "name"=>"Bob"}>]
#
# df.where(df.age == 2).collect
# # => [#<Row {"age"=>2, "name"=>"Alice"}>]
#
# df.filter("age > 3").collect
# # => [#<Row {"age"=>5, "name"=>"Bob"}>]
#
# df.where("age = 2").collect
# # => [#<Row {"age"=>2, "name"=>"Alice"}>]
#
def filter(condition)
case condition
when String
new_jdf = jdf.filter(condition)
when Column
new_jdf = jdf.filter(condition.jcolumn)
else
raise ArgumentError, 'Condition must be String or Column'
end
DataFrame.new(new_jdf, sql_context)
end
# Limits the result count to the number specified.
def limit(num)
new_jdf = jdf.limit(num)
DataFrame.new(new_jdf, sql_context)
end
def register_temp_table name
jdf.registerTempTable(name)
end
def write
DataFrameWriter.new(self)
end
alias_method :where, :filter
end
end
end