如何将pysparkDataframe存储到hbase中

bbuxkriu  于 2021-06-09  发布在  Hbase
关注(0)|答案(1)|浏览(447)

我有一个将pyspark流数据转换为Dataframe的代码。我需要将这个Dataframe存储到hbase中。另外帮我写代码。

import sys
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import Row, SparkSession

def getSparkSessionInstance(sparkConf):
if ('sparkSessionSingletonInstance' not in globals()):
    globals()['sparkSessionSingletonInstance'] = SparkSession\
        .builder\
        .config(conf=sparkConf)\
        .getOrCreate()
return globals()['sparkSessionSingletonInstance']

if __name__ == "__main__":
if len(sys.argv) != 3:
    print("Usage: sql_network_wordcount.py <hostname> <port> ", 
file=sys.stderr)
    exit(-1)
host, port = sys.argv[1:]
sc = SparkContext(appName="PythonSqlNetworkWordCount")
ssc = StreamingContext(sc, 1)
lines = ssc.socketTextStream(host, int(port))

def process(time, rdd):
    print("========= %s =========" % str(time))

    try:
        words = rdd.map(lambda line :line.split(" ")).collect()
        spark = getSparkSessionInstance(rdd.context.getConf())
        linesDataFrame = spark.createDataFrame(words,schema=["lat","lon"])

        linesDataFrame.show()
except :
pass

lines.foreachRDD(process)
ssc.start()
ssc.awaitTermination()
iswrvxsc

iswrvxsc1#

您可以使用spark hbase connector从spark访问hbase,它提供了一个低层和底层的api RDD 以及 Dataframes .
连接器要求您定义 Schema 用于hbase表。下面是为名为的hbase表定义的模式示例 table1 ,行键作为键和许多列(col1-col8)。请注意 rowkey 还必须详细定义为列(col0),该列具有特定的cf(rowkey)。

def catalog = '{
        "table":{"namespace":"default", "name":"table1"},\
        "rowkey":"key",\
        "columns":{\
          "col0":{"cf":"rowkey", "col":"key", "type":"string"},\
          "col1":{"cf":"cf1", "col":"col1", "type":"boolean"},\
          "col2":{"cf":"cf1", "col":"col2", "type":"double"},\
          "col3":{"cf":"cf1", "col":"col3", "type":"float"},\
          "col4":{"cf":"cf1", "col":"col4", "type":"int"},\
          "col5":{"cf":"cf2", "col":"col5", "type":"bigint"},\
          "col6":{"cf":"cf2", "col":"col6", "type":"smallint"},\
          "col7":{"cf":"cf2", "col":"col7", "type":"string"},\
          "col8":{"cf":"cf2", "col":"col8", "type":"tinyint"}\
        }\
      }'

根据Dataframe的架构定义目录后,可以使用以下方法将Dataframe写入hbase:

df.write\
.options(catalog=catalog)\
.format("org.apache.spark.sql.execution.datasources.hbase")\
.save()

要从hbase读取数据:

df = spark.\
read.\
format("org.apache.spark.sql.execution.datasources.hbase").\
option(catalog=catalog).\
load()

在提交spark应用程序时,需要包含spark hbase connector包,如下所示。

pyspark --packages com.hortonworks:shc-core:1.1.1-2.1-s_2.11 --repositories http://repo.hortonworks.com/content/groups/public/

相关问题