读取和存数据:
hivre 中读取直接就可以写SQL,逻辑类似在hive 中一样,但从其他数据源中读取数据时,需要先用registerTempTable命表名
,再进行查询。这些数据也可以使用rdd操作函数
#从hive中读取:
from pyspark import HiveContext
from pyspark import SparkContext
from pyspark import SparkConf
conf=SparkConf().setAppName("miniProject").setMaster("local[*]")
sc=SparkContext.getOrCreate(conf)
hiveCtx = HiveContext(sc)
rows = hiveCtx.sql("select key from table")#括号中直接写SQL就可以了
keys = rows.map(lambda row: row[0])#获取key,这里的操作就跟使用pyspark 差不多了
#parquet中读取:
rows = hiveCtx.parquetFile(path)
tabl = rows.registerTempTable('表名')
data = hiveCtx.sql('SQL语句')
#从Json中读取:
inp = h_text.read.json('./tweet.json')#读进来之后就自动变成schemaRDD,对于没有值的列就为None
创建schemaRDD:
除了用上述的方法读数据,还可以基于RDD创建:
#单条
hera = sc.parallelize([Row(name='kobe',faco="coffee")])
harardd = h_text.inferSchema(hera)
harardd.registerTempTable('harardd')
#批量:python中实际上就是把一行一行的转化为Row,scala中有先建立结构再导入的方式
lines = sc.textFile("data_sql.txt")
parts = lines.map(lambda l: l.split(","))
employee = parts.map(lambda p: Row(oid =p[0],name=p[1],age=int(p[2]),salary=int(p[3])))
harardd = h_text.inferSchema(employee)
harardd.registerTempTable('harardd')
编写自定义函数UDF:
hiveCtx.registerFunction('函数名',lambda x: len(x),IntegerType())#返回值需要参考schemaRDD中对应类型指定
hiveCtx.sql('SQL')#就可以调用函数了
sparkSql性能:
可以通过Beeline设置 参见p 158