PySpark is an interface for Apache Spark in Python. It not only allows you to write Spark applications using Python APIs, but also provides the PySpark shell for interactively analyzing your data in a distributed environment.
# A example from https://spark.apache.org/docs/latest/sql-data-sources-hive-tables.htmlfromos.pathimportabspathfrompyspark.sqlimportSparkSessionfrompyspark.sqlimportRow# warehouse_location points to the default location for managed databases and tableswarehouse_location=abspath('spark-warehouse')spark=SparkSession \
.builder \
.appName("Python Spark SQL Hive integration example") \
.config("spark.sql.warehouse.dir",warehouse_location) \
.enableHiveSupport() \
.getOrCreate()# spark is an existing SparkSessionspark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")spark.sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")# The results of SQL queries are themselves DataFrames and support all normal functions.sqlDF=spark.sql("SELECT key, value FROM src WHERE key < 10 ORDER BY key")
## Licensed to the Apache Software Foundation (ASF) under one or more# contributor license agreements. See the NOTICE file distributed with# this work for additional information regarding copyright ownership.# The ASF licenses this file to You under the Apache License, Version 2.0# (the "License"); you may not use this file except in compliance with# the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#"""
An interactive shell.
This file is designed to be launched as a PYTHONSTARTUP script.
"""importatexitimportosimportplatformimportwarningsimportpy4jfrompysparkimportSparkConffrompyspark.contextimportSparkContextfrompyspark.sqlimportSparkSession,SQLContextifos.environ.get("SPARK_EXECUTOR_URI"):SparkContext.setSystemProperty("spark.executor.uri",os.environ["SPARK_EXECUTOR_URI"])SparkContext._ensure_initialized()try:# Try to access HiveConf, it will raise exception if Hive is not addedconf=SparkConf()ifconf.get('spark.sql.catalogImplementation','hive').lower()=='hive':SparkContext._jvm.org.apache.hadoop.hive.conf.HiveConf()spark=SparkSession.builder\
.enableHiveSupport()\
.getOrCreate()else:spark=SparkSession.builder.getOrCreate()exceptpy4j.protocol.Py4JError:ifconf.get('spark.sql.catalogImplementation','').lower()=='hive':warnings.warn("Fall back to non-hive support because failing to access HiveConf, ""please make sure you build spark with hive")spark=SparkSession.builder.getOrCreate()exceptTypeError:ifconf.get('spark.sql.catalogImplementation','').lower()=='hive':warnings.warn("Fall back to non-hive support because failing to access HiveConf, ""please make sure you build spark with hive")spark=SparkSession.builder.getOrCreate()sc=spark.sparkContextsql=spark.sqlatexit.register(lambda:sc.stop())# for compatibilitysqlContext=spark._wrappedsqlCtx=sqlContextprint("""Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version %s /_/
"""%sc.version)print("Using Python version %s (%s, %s)"%(platform.python_version(),platform.python_build()[0],platform.python_build()[1]))print("SparkSession available as 'spark'.")# The ./bin/pyspark script stores the old PYTHONSTARTUP value in OLD_PYTHONSTARTUP,# which allows us to execute the user's PYTHONSTARTUP file:_pythonstartup=os.environ.get('OLD_PYTHONSTARTUP')if_pythonstartupandos.path.isfile(_pythonstartup):withopen(_pythonstartup)asf:code=compile(f.read(),_pythonstartup,'exec')exec(code)
# A example from https://docs.microsoft.com/en-us/azure/databricks/spark/latest/spark-sql/spark-pandasimportnumpyasnpimportpandasaspd# Enable Arrow-based columnar data transfersspark.conf.set("spark.sql.execution.arrow.enabled","true")# Generate a pandas DataFramepdf=pd.DataFrame(np.random.rand(100,3))# Create a Spark DataFrame from a pandas DataFrame using Arrowdf=spark.createDataFrame(pdf)# Convert the Spark DataFrame back to a pandas DataFrame using Arrowresult_pdf=df.select("*").toPandas()
这部分再Mark一个关于 collect() 的小点,总之数据量比较大的时候就不要用这个方法。
The collect() function returns a list that contains all the elements in this RDD, and should only be used if the resulting array is expected to be ==small==, as all the data is loaded in a driver’s memory, in which case we lose the benefits of distributing the data around a cluster of Spark instances.
spark_df.createOrReplaceTempView("myTempTableName")spark.sql("drop table if exists dbName.tableName")spark.sql("create table dbName.tableName as select * from myTempTableName")