forked from sparklyr/sparklyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
419 lines (303 loc) · 15.9 KB
/
README.Rmd
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
---
title: "sparklyr: R interface for Apache Spark"
output:
github_document:
fig_width: 9
fig_height: 5
---
![Github workflow status](https://github.com/sparklyr/sparklyr/workflows/CI/badge.svg) [![AppVeyor build status](https://ci.appveyor.com/api/projects/status/lxaj4kgu3liovmhp?svg=true)](https://ci.appveyor.com/project/yl790/sparklyr-ybp7x) [![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/sparklyr)](https://cran.r-project.org/package=sparklyr) <a href="https://www.r-pkg.org/pkg/sparklyr"><img src="https://cranlogs.r-pkg.org/badges/sparklyr?color=brightgreen" style=""></a> [![codecov](https://codecov.io/gh/sparklyr/sparklyr/branch/master/graph/badge.svg)](https://codecov.io/gh/sparklyr/sparklyr) [![Join the chat at https://gitter.im/sparklyr/sparklyr](https://badges.gitter.im/sparklyr/sparklyr.svg)](https://gitter.im/sparklyr/sparklyr?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<img src="tools/readme/sparklyr-illustration.png" width="320" align="right" style="margin-left: 20px; margin-right: 20px"/>
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = TRUE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(fig.path = "tools/readme/", dev = "png")
```
- Install and connect to [Spark](http://spark.apache.org/) using YARN, Mesos, Livy or Kubernetes.
- Use [dplyr](https://spark.rstudio.com/dplyr/) to filter and aggregate Spark datasets and [streams](https://spark.rstudio.com/guides/streaming/) then bring them into R for analysis and visualization.
- Use [MLlib](http://spark.apache.org/docs/latest/mllib-guide.html), [H2O](https://spark.rstudio.com/guides/h2o/), [XGBoost](https://github.com/rstudio/sparkxgb) and [GraphFrames](https://github.com/rstudio/graphframes) to train models at scale in Spark.
- Create interoperable machine learning [pipelines](https://spark.rstudio.com/guides/pipelines/) and productionize them with [MLeap](https://spark.rstudio.com/guides/mleap/).
- Create [extensions](https://spark.rstudio.com/extensions.html) that call the full Spark API or run [distributed R](https://spark.rstudio.com/guides/distributed-r/) code to support new functionality.
## Installation
You can install the **sparklyr** package from [CRAN](https://CRAN.r-project.org) as follows:
```{r, eval=FALSE}
install.packages("sparklyr")
```
You should also install a local version of Spark for development purposes:
```{r, eval=FALSE}
library(sparklyr)
spark_install()
```
To upgrade to the latest version of sparklyr, run the following command and restart your r session:
```{r, eval=FALSE}
install.packages("devtools")
devtools::install_github("sparklyr/sparklyr")
```
## Connecting to Spark
You can connect to both local instances of Spark as well as remote Spark clusters. Here we'll connect to a local instance of Spark via the [spark_connect](https://spark.rstudio.com/reference/spark-connections/) function:
```{r sparklyr-connect, message=FALSE}
library(sparklyr)
sc <- spark_connect(master = "local")
```
The returned Spark connection (`sc`) provides a remote dplyr data source to the Spark cluster.
For more information on connecting to remote Spark clusters see the [Deployment](https://spark.rstudio.com/deployment.html) section of the sparklyr website.
## Using dplyr
We can now use all of the available dplyr verbs against the tables within the cluster.
We'll start by copying some datasets from R into the Spark cluster (note that you may need to install the nycflights13 and Lahman packages in order to execute this code):
```{r, eval=FALSE}
install.packages(c("nycflights13", "Lahman"))
```
```{r dplyr-copy, message=FALSE}
library(dplyr)
iris_tbl <- copy_to(sc, iris, overwrite = TRUE)
flights_tbl <- copy_to(sc, nycflights13::flights, "flights", overwrite = TRUE)
batting_tbl <- copy_to(sc, Lahman::Batting, "batting", overwrite = TRUE)
src_tbls(sc)
```
To start with here's a simple filtering example:
```{r dplyr-filter}
# filter by departure delay and print the first few records
flights_tbl %>% filter(dep_delay == 2)
```
[Introduction to dplyr](https://CRAN.R-project.org/package=dplyr) provides additional dplyr examples you can try. For example, consider the last example from the tutorial which plots data on flight delays:
```{r dplyr-ggplot2}
delay <- flights_tbl %>%
group_by(tailnum) %>%
summarise(count = n(), dist = mean(distance), delay = mean(arr_delay)) %>%
filter(count > 20, dist < 2000, !is.na(delay)) %>%
collect
# plot delays
library(ggplot2)
ggplot(delay, aes(dist, delay)) +
geom_point(aes(size = count), alpha = 1/2) +
geom_smooth() +
scale_size_area(max_size = 2)
```
### Window Functions
dplyr [window functions](https://CRAN.R-project.org/package=dplyr) are also supported, for example:
```{r dplyr-window}
batting_tbl %>%
select(playerID, yearID, teamID, G, AB:H) %>%
arrange(playerID, yearID, teamID) %>%
group_by(playerID) %>%
filter(min_rank(desc(H)) <= 2 & H > 0)
```
For additional documentation on using dplyr with Spark see the [dplyr](https://spark.rstudio.com/dplyr.html) section of the sparklyr website.
## Using SQL
It's also possible to execute SQL queries directly against tables within a Spark cluster. The `spark_connection` object implements a [DBI](https://github.com/rstats-db/DBI) interface for Spark, so you can use `dbGetQuery` to execute SQL and return the result as an R data frame:
```{r sql-dbi}
library(DBI)
iris_preview <- dbGetQuery(sc, "SELECT * FROM iris LIMIT 10")
iris_preview
```
## Machine Learning
You can orchestrate machine learning algorithms in a Spark cluster via the [machine learning](http://spark.apache.org/docs/latest/mllib-guide.html) functions within **sparklyr**. These functions connect to a set of high-level APIs built on top of DataFrames that help you create and tune machine learning workflows.
Here's an example where we use [ml_linear_regression](https://spark.rstudio.com/reference/ml_linear_regression/) to fit a linear regression model. We'll use the built-in `mtcars` dataset, and see if we can predict a car's fuel consumption (`mpg`) based on its weight (`wt`), and the number of cylinders the engine contains (`cyl`). We'll assume in each case that the relationship between `mpg` and each of our features is linear.
```{r}
# copy mtcars into spark
mtcars_tbl <- copy_to(sc, mtcars, overwrite = TRUE)
# transform our data set, and then partition into 'training', 'test'
partitions <- mtcars_tbl %>%
filter(hp >= 100) %>%
mutate(cyl8 = cyl == 8) %>%
sdf_partition(training = 0.5, test = 0.5, seed = 1099)
# fit a linear model to the training dataset
fit <- partitions$training %>%
ml_linear_regression(response = "mpg", features = c("wt", "cyl"))
fit
```
For linear regression models produced by Spark, we can use `summary()` to learn a bit more about the quality of our fit, and the statistical significance of each of our predictors.
```{r}
summary(fit)
```
Spark machine learning supports a wide array of algorithms and feature transformations and as illustrated above it's easy to chain these functions together with dplyr pipelines. To learn more see the [machine learning](https://spark.rstudio.com/mlib/) section.
## Reading and Writing Data
You can read and write data in CSV, JSON, and Parquet formats. Data can be stored in HDFS, S3, or on the local filesystem of cluster nodes.
```{r}
temp_csv <- tempfile(fileext = ".csv")
temp_parquet <- tempfile(fileext = ".parquet")
temp_json <- tempfile(fileext = ".json")
spark_write_csv(iris_tbl, temp_csv)
iris_csv_tbl <- spark_read_csv(sc, "iris_csv", temp_csv)
spark_write_parquet(iris_tbl, temp_parquet)
iris_parquet_tbl <- spark_read_parquet(sc, "iris_parquet", temp_parquet)
spark_write_json(iris_tbl, temp_json)
iris_json_tbl <- spark_read_json(sc, "iris_json", temp_json)
src_tbls(sc)
```
## Distributed R
You can execute arbitrary r code across your cluster using `spark_apply`. For example, we can apply `rgamma` over `iris` as follows:
```{r}
spark_apply(iris_tbl, function(data) {
data[1:4] + rgamma(1,2)
})
```
You can also group by columns to perform an operation over each group of rows and make use of any package within the closure:
```{r}
spark_apply(
iris_tbl,
function(e) broom::tidy(lm(Petal_Width ~ Petal_Length, e)),
columns = c("term", "estimate", "std.error", "statistic", "p.value"),
group_by = "Species"
)
```
## Extensions
The facilities used internally by sparklyr for its dplyr and machine learning interfaces are available to extension packages. Since Spark is a general purpose cluster computing system there are many potential applications for extensions (e.g. interfaces to custom machine learning pipelines, interfaces to 3rd party Spark packages, etc.).
Here's a simple example that wraps a Spark text file line counting function with an R function:
```{r}
# write a CSV
tempfile <- tempfile(fileext = ".csv")
write.csv(nycflights13::flights, tempfile, row.names = FALSE, na = "")
# define an R interface to Spark line counting
count_lines <- function(sc, path) {
spark_context(sc) %>%
invoke("textFile", path, 1L) %>%
invoke("count")
}
# call spark to count the lines of the CSV
count_lines(sc, tempfile)
```
To learn more about creating extensions see the [Extensions](https://spark.rstudio.com/extensions.html) section of the sparklyr website.
## Table Utilities
You can cache a table into memory with:
```{r, eval=FALSE}
tbl_cache(sc, "batting")
```
and unload from memory using:
```{r, eval=FALSE}
tbl_uncache(sc, "batting")
```
## Connection Utilities
You can view the Spark web console using the `spark_web` function:
```{r, eval=FALSE}
spark_web(sc)
```
You can show the log using the `spark_log` function:
```{r}
spark_log(sc, n = 10)
```
Finally, we disconnect from Spark:
```{r}
spark_disconnect(sc)
```
## RStudio IDE
The latest RStudio [Preview Release](https://www.rstudio.com/products/rstudio/download/preview/) of the RStudio IDE includes integrated support for Spark and the sparklyr package, including tools for:
- Creating and managing Spark connections
- Browsing the tables and columns of Spark DataFrames
- Previewing the first 1,000 rows of Spark DataFrames
Once you've installed the sparklyr package, you should find a new **Spark** pane within the IDE. This pane includes a **New Connection** dialog which can be used to make connections to local or remote Spark instances:
<img src="tools/readme/spark-connect.png" class="screenshot" width=389 />
Once you've connected to Spark you'll be able to browse the tables contained within the Spark cluster and preview Spark DataFrames using the standard RStudio data viewer:
<img src="tools/readme/spark-dataview.png" class="screenshot" width=639 />
You can also connect to Spark through [Livy](http://livy.io) through a new connection dialog:
<img src="tools/readme/spark-connect-livy.png" class="screenshot" width=389 />
<div style="margin-bottom: 15px;"></div>
The RStudio IDE features for sparklyr are available now as part of the [RStudio Preview Release](https://www.rstudio.com/products/rstudio/download/preview/).
## Using H2O
[rsparkling](https://cran.r-project.org/package=rsparkling) is a CRAN package from [H2O](https://h2o.ai/) that extends [sparklyr](https://spark.rstudio.com/) to provide an interface into [Sparkling Water](https://github.com/h2oai/sparkling-water). For instance, the following example installs, configures and runs [h2o.glm](http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/glm.html):
```{r results='hide', message=FALSE, eval=FALSE}
library(rsparkling)
library(sparklyr)
library(dplyr)
library(h2o)
sc <- spark_connect(master = "local", version = "2.3.2")
mtcars_tbl <- copy_to(sc, mtcars, "mtcars", overwrite = TRUE)
mtcars_h2o <- as_h2o_frame(sc, mtcars_tbl, strict_version_check = FALSE)
mtcars_glm <- h2o.glm(x = c("wt", "cyl"),
y = "mpg",
training_frame = mtcars_h2o,
lambda_search = TRUE)
```
```{r eval=FALSE}
mtcars_glm
```
```
## Model Details:
## ==============
##
## H2ORegressionModel: glm
## Model ID: GLM_model_R_1527265202599_1
## GLM Model: summary
## family link regularization
## 1 gaussian identity Elastic Net (alpha = 0.5, lambda = 0.1013 )
## lambda_search
## 1 nlambda = 100, lambda.max = 10.132, lambda.min = 0.1013, lambda.1se = -1.0
## number_of_predictors_total number_of_active_predictors
## 1 2 2
## number_of_iterations training_frame
## 1 100 frame_rdd_31_ad5c4e88ec97eb8ccedae9475ad34e02
##
## Coefficients: glm coefficients
## names coefficients standardized_coefficients
## 1 Intercept 38.941654 20.090625
## 2 cyl -1.468783 -2.623132
## 3 wt -3.034558 -2.969186
##
## H2ORegressionMetrics: glm
## ** Reported on training data. **
##
## MSE: 6.017684
## RMSE: 2.453097
## MAE: 1.940985
## RMSLE: 0.1114801
## Mean Residual Deviance : 6.017684
## R^2 : 0.8289895
## Null Deviance :1126.047
## Null D.o.F. :31
## Residual Deviance :192.5659
## Residual D.o.F. :29
## AIC :156.2425
```
```{r eval=FALSE}
spark_disconnect(sc)
```
## Connecting through Livy
[Livy](https://github.com/cloudera/livy) enables remote connections to Apache Spark clusters. However, please notice that connecting to Spark clusters through Livy is much slower than any other connection method.
Before connecting to Livy, you will need the connection information to an existing service running Livy. Otherwise, to test `livy` in your local environment, you can install it and run it locally as follows:
```{r eval=FALSE}
livy_install()
```
```{r livy-start}
livy_service_start()
```
To connect, use the Livy service address as `master` and `method = "livy"` in `spark_connect`. Once connection completes, use `sparklyr` as usual, for instance:
```{r livy-connect}
sc <- spark_connect(master = "http://localhost:8998", method = "livy", version = "2.4.0")
copy_to(sc, iris, overwrite = TRUE)
spark_disconnect(sc)
```
Once you are done using `livy` locally, you should stop this service with:
```{r livy-stop}
livy_service_stop()
```
To connect to remote `livy` clusters that support basic authentication connect as:
```{r eval=FALSE}
config <- livy_config(username="<username>", password="<password>")
sc <- spark_connect(master = "<address>", method = "livy", config = config)
spark_disconnect(sc)
```
## Connecting through Databricks Connect
[Databricks Connect](https://docs.databricks.com/dev-tools/databricks-connect.html#databricks-connect) allows you to connect
sparklyr to a remote Databricks Cluster. You can install [Databricks Connect python package](https://pypi.org/project/databricks-connect/) and use it to submit Spark jobs written in sparklyr APIs and have them execute remotely on a Databricks cluster instead of in the local Spark session.
To use sparklyr with Databricks Connect first launch a Cluster on Databricks. Then follow [these instructions](https://docs.databricks.com/dev-tools/databricks-connect.html#client-setup) to setup the client:
1. Make sure pyspark is not installed
2. Install the Databricks Connect python package. The latest supported version is 6.4.1.
3. Run `databricks-connect configure` and provide the configuration information
* Databricks account URL of the form `https://<account>.cloud.databricks.com`.
* [User token](https://docs.databricks.com/dev-tools/api/latest/authentication.html#token-management)
* Cluster ID
* Port (default port number is `15001`)
To configure `sparklyr` with Databricks Connect, set the following environment variables:
```{bash, eval=FALSE}
export SPARK_VERSION=2.4.4
```
Now simply create a spark connection as follows
```{r, eval=FALSE}
spark_home <- system("databricks-connect get-spark-home")
sc <- spark_connect(method = "databricks",
spark_home = spark_home)
copy_to(sc, iris, overwrite = TRUE)
```
<img src="tools/readme/databricks-connect.png" class="screenshot" width=750 />
```{r eval=FALSE}
spark_disconnect(sc)
```