Back to home page

OSCL-LXR

 
 

    


0001 #
0002 # Licensed to the Apache Software Foundation (ASF) under one or more
0003 # contributor license agreements.  See the NOTICE file distributed with
0004 # this work for additional information regarding copyright ownership.
0005 # The ASF licenses this file to You under the Apache License, Version 2.0
0006 # (the "License"); you may not use this file except in compliance with
0007 # the License.  You may obtain a copy of the License at
0008 #
0009 #    http://www.apache.org/licenses/LICENSE-2.0
0010 #
0011 # Unless required by applicable law or agreed to in writing, software
0012 # distributed under the License is distributed on an "AS IS" BASIS,
0013 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014 # See the License for the specific language governing permissions and
0015 # limitations under the License.
0016 #
0017 
0018 """
0019 Read data file users.parquet in local Spark distro:
0020 
0021 $ cd $SPARK_HOME
0022 $ export AVRO_PARQUET_JARS=/path/to/parquet-avro-1.5.0.jar
0023 $ ./bin/spark-submit --driver-class-path /path/to/example/jar \\
0024         --jars $AVRO_PARQUET_JARS \\
0025         ./examples/src/main/python/parquet_inputformat.py \\
0026         examples/src/main/resources/users.parquet
0027 <...lots of log output...>
0028 {u'favorite_color': None, u'name': u'Alyssa', u'favorite_numbers': [3, 9, 15, 20]}
0029 {u'favorite_color': u'red', u'name': u'Ben', u'favorite_numbers': []}
0030 <...more log output...>
0031 """
0032 from __future__ import print_function
0033 
0034 import sys
0035 
0036 from pyspark.sql import SparkSession
0037 
0038 if __name__ == "__main__":
0039     if len(sys.argv) != 2:
0040         print("""
0041         Usage: parquet_inputformat.py <data_file>
0042 
0043         Run with example jar:
0044         ./bin/spark-submit --driver-class-path /path/to/example/jar \\
0045                 /path/to/examples/parquet_inputformat.py <data_file>
0046         Assumes you have Parquet data stored in <data_file>.
0047         """, file=sys.stderr)
0048         sys.exit(-1)
0049 
0050     path = sys.argv[1]
0051 
0052     spark = SparkSession\
0053         .builder\
0054         .appName("ParquetInputFormat")\
0055         .getOrCreate()
0056 
0057     sc = spark.sparkContext
0058 
0059     parquet_rdd = sc.newAPIHadoopFile(
0060         path,
0061         'org.apache.parquet.avro.AvroParquetInputFormat',
0062         'java.lang.Void',
0063         'org.apache.avro.generic.IndexedRecord',
0064         valueConverter='org.apache.spark.examples.pythonconverters.IndexedRecordToJavaConverter')
0065     output = parquet_rdd.map(lambda x: x[1]).collect()
0066     for k in output:
0067         print(k)
0068 
0069     spark.stop()