这是我的代码。我在数据块中运行它。
library(sparklyr)
library(dplyr)
library(arrow)
sc <- spark_connect(method = "databricks")
tbl_change_db(sc, "prod")
trip_ids <- spark_read_table(sc, "signals",memory=F) %>%
slice_sample(10) %>%
pull(trip_identifier)
尽管我只查询了 10 个样本,但代码非常慢并且需要花费一个小时才能运行。 这是为什么?有没有办法提高性能?
谢谢!
其他答案和评论已经涵盖了为什么查询花费了这么长时间(你比你想要的更早地将整个表拉入驱动程序/R),但我想包括一个真正采样数据的例子和另一个为您提供更多控制的方法(即使用 SparkSQL 的方法)。在使用 Spark 时,我尝试将所有繁重的工作作为实际的 SQL 查询来完成,因此我更喜欢选项 2,但我将两者都包括在内,以防一个比另一个更有帮助。
library(sparklyr)
library(dplyr)
sc = spark_connect(method = "databricks")
tbl_change_db(sc, "prod")
# Option 1, using a fraction (proportion in this case) to pull a random sample
spark_read_table(sc, "signals", memory = FALSE) %>%
select(trip_identifier) %>%
sdf_sample(fraction = .0001, replacement = FALSE, seed = NULL) %>%
collect() %>% #this is not necessary, but it makes the pull-down to R explicit
pull(trip_identifier)
# Option 2, using SparkSQL to run the query as you intended (sampling 10 rows)
sc %>%
sdf_sql("SELECT trip_identifier FROM signals TABLESAMPLE (10 ROWS)") %>%
collect() %>% #this is not necessary, but it makes the pull-down to R explicit
pull(trip_identifier)