PySpark-Recipes : 写数据到Hive(local data)

把本地数据导入到Hive

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('write_data').getOrCreate()
import pyspark.sql.functions as F
from pyspark.sql.types import *    # Row, StructType, StructField, StringType, IntegerType

建库,建表

hive> create database if not exists Test;
hive> show Test;
hive> create table if not exists Test.wjh_test(
>phone string,
>day int);

hive> show tables;

在这里插入图片描述

少量写入数据

hive> use ima;
hive> insert into wjh_test values('13233344421', 20190808);
hive> insert into wjh_test values('13666655532', 20190909);
hive> select * from wjh_test:

在这里插入图片描述

大量写入数据(本地文件,非hdfs路径下)

# load local data
f = open('/home/今晚打老虎/phone.csv')
# transform > RDD
rdd = spark.sparkContext.parallelize(f).map(lambda x : x.strip('\n').split(','))
#rdd = rdd.map(lambda line: Row(line[0], int(line[1])))
schema = StructType([StructField('phone', StringType(), True), StructField('day', StringType(), True)])
# schema = StructType().add('phone', 'string').add('day', 'string')
df = spark.createDataFrame(rdd, schema)
df.registerTempTable('tempTable')
# 选择表
spark.sql('use Test')
spark.sql('insert into wjh_test select * from tempTable')

查询写入结果

  • spark.sql(‘select * from wjh_test limit 10’).show()
  • hive>select * from wjh_test limit 10;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值