目录
- 准备工作
- 确认hive server2的ip、端口和访问权限
- Mac本地安装Rstudio
- Rstudio安装jar包
- 创建R连接hive脚本函数
- 测试
- 调用R脚本的函数
1 准备工作
1.1 确认hive server2的ip、端口和访问权限
- 找维护hadoop的同事, 确认hive server2的ip和端口
- 确认hive server的ip在本地能否ping通
打开终端, 输入ping ip地址
, 如出现下图则表示能够ping通,
3. 再次确认hive server2的端口在本地能否访问
这里需要用到telnet, 因此先在终端配置telnet
- 打开终端, 输入
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
- 下载成功后, 输入
brew install telnet
- 使用telnet确认hive server2的端口在本地能否访问, 因此继续在终端输入
telnet ip 端口
如果出现Connected to ip.
的提示则说明可访问啦, 反之如果一直显示Trying ip...
则说明不可访问, 要么是ip和端口错误, 要么是可能没有访问的权限, 需找hadoop同事确认清楚, 或者申请权限去~
1.2 Mac本地安装Rstudio
首先说明: R是运行环境, Rstudio是开发工具(为了方便使用R语言而生).
因此需先后安装:
1) R语言环境: https://cran.r-project.org/
2) Rstudio: https://www.rstudio.com/products/rstudio/download/
1.3 Rstudio安装jar包
在Rconsole输入
install.packages('DBI')
install.packages('rJava')
install.packages('RJDBC')
devtools::install_github("lengyuyeke/RHJDBC") #注意: 有的Rstudio版本不支持安装RHJDBC,直接github上安装可解决版本限制问题
2 创建R连接hive脚本函数
可将以下另存为一个R脚本, 比如起名叫function.R
, 之后每次连接hive的时候, 直接调用本地的该脚本即可, 避免每次都写一大坨.
options(java.parameters = "-Xmx8g") # set jvm
library(DBI)
library(RJDBC)
# 连接 Hive
init_jdbc <- function() {
require(RHJDBC)
cp <- dir(system.file("java", package = "RHJDBC"), full.names = TRUE) # you can use your own jdbc driver
.jinit(classpath = cp) # init
drv <- JDBC("org.apache.hive.jdbc.HiveDriver") # set driver
con <- dbConnect(drv,
"jdbc:hive2://ip:终端/default",
"username",
"password"
) # set connection,url,username,password
class(con) <- "JHDBCConnection" # change the class of con
con
}
# 查询 Hive
get_hive_query <- function(query) {
print(query)
conn <- init_jdbc()
data <- try(dbGetQuery(conn, query), silent = TRUE)
dbDisconnect(conn)
if (class(data) %in% c("error", "try-error")) {
return()
}
if (nrow(data) > 0) {
colnames(data) <- gsub("(.*).(.*)", "2", colnames(data))
data.table::setDT(data)
data
}
}
3 测试
dat<- get_hive_query("select * from tmp.test")
4 调用R脚本的函数
source("//Users/hanqianyun/Desktop/function.R")
dat<- get_hive_query("select * from tmp.test")
over~