Load table from bigquery to spark cluster with pyspark script

I have a data table loaded in bigquery and I want to import it in my spark cluster via the pyspark.py file.

I saw examples in Dataproc + BigQuery - any available? that there was a way to load a bigquery table in a spark cluster using scala, but is there a way to do this in a pyspark script?

+4
source share
1 answer

This comes from @MattJ in this matter . Here's an example of connecting to BigQuery in Spark and doing word counting.

import json
import pyspark
sc = pyspark.SparkContext()

hadoopConf=sc._jsc.hadoopConfiguration()
hadoopConf.get("fs.gs.system.bucket")

conf = {"mapred.bq.project.id": "<project_id>", "mapred.bq.gcs.bucket": "<bucket>",
    "mapred.bq.input.project.id": "publicdata", 
    "mapred.bq.input.dataset.id":"samples", 
    "mapred.bq.input.table.id": "shakespeare"  }

tableData = sc.newAPIHadoopRDD(
    "com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat",
    "org.apache.hadoop.io.LongWritable", "com.google.gson.JsonObject", 
    conf=conf).map(lambda k: json.loads(k[1])).map(lambda x: (x["word"],
    int(x["word_count"]))).reduceByKey(lambda x,y: x+y)

print tableData.take(10)

<project_id> <bucket> .

+4

Source: https://habr.com/ru/post/1613284/


All Articles