Search code examples
pysparkgoogle-bigquerygoogle-cloud-dataproc

BigQuery connector ClassNotFoundException in PySpark on Dataproc


I'm trying to run a script in PySpark, using Dataproc.

The script is kind of a merge between this example and what I need to do, as I wanted to check if everything works. Obviously, it doesn't.

The error I get is:

File "/usr/lib/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.newAPIHadoopRDD. : java.lang.ClassNotFoundException: com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat

I made sure I have all the jars, added some new jars as suggested in other similar posts. I also checked the SPARK_HOME variable.

Below you can see the code; the error appears when trying to instantiate table_data.

"""BigQuery I/O PySpark example."""
from __future__ import absolute_import
import json
import pprint
import subprocess
import pyspark
from pyspark.sql import SQLContext

sc = pyspark.SparkContext()

bucket = sc._jsc.hadoopConfiguration().get('fs.gs.system.bucket')
project = sc._jsc.hadoopConfiguration().get('fs.gs.project.id')
input_directory = 'gs://{}/hadoop/tmp/bigquery/pyspark_input'.format(bucket)

conf = {
    'mapred.bq.project.id': project,
    'mapred.bq.gcs.bucket': bucket,
    'mapred.bq.temp.gcs.path': input_directory,
    'mapred.bq.input.project.id': 'publicdata',
    'mapred.bq.input.dataset.id': 'samples',
    'mapred.bq.input.table.id': 'shakespeare',
}

output_dataset = 'wordcount_dataset'
output_table = 'wordcount_output'

table_data = sc.newAPIHadoopRDD(
    'com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat',
    'org.apache.hadoop.io.LongWritable',
    'com.google.gson.JsonObject',
    conf=conf)

Solution

  • As pointed out in the example, you need to include BigQuery connector jar when submitting the job.

    Through Dataproc jobs API:

    gcloud dataproc jobs submit pyspark --cluster=${CLUSTER} \
        /path/to/your/script.py \
        --jars=gs://hadoop-lib/bigquery/bigquery-connector-hadoop2-latest.jar
    

    or spark-submit from inside the cluster:

    spark-submit --jars=gs://hadoop-lib/bigquery/bigquery-connector-hadoop2-latest.jar \
        /path/to/your/script.py