6

I have a Dataframe, from which a create a temporary view in order to run sql queries. After a couple of sql queries, I'd like to convert the output of sql query to a new Dataframe. The reason I want data back in Dataframe is so that I can save it to blob storage.

So, the question is: what is the proper way to convert sql query output to Dataframe?

Here's the code I have so far:

%scala
//read data from Azure blob
...
var df = spark.read.parquet(some_path)

// create temp view
df.createOrReplaceTempView("data_sample")

%sql
//have some sqlqueries, the one below is just an example
SELECT
   date,
   count(*) as cnt
FROM
   data_sample
GROUP BY
   date

//Now I want to have a dataframe  that has the above sql output. How to do that?
Preferably the code would be in python or scala.


3 Answers 3

7

Scala:

var df = spark.sql(s"""
SELECT
   date,
   count(*) as cnt
FROM
   data_sample
GROUP BY
   date
""")

PySpark:

df = spark.sql(f'''
SELECT
   date,
   count(*) as cnt
FROM
   data_sample
GROUP BY
   date
''')
Sign up to request clarification or add additional context in comments.

3 Comments

Can the sql string be parametrized? Something like f’’’ SELECT date + {timezone} as date, … ‘’’ where timezone is a parameter?
yes, like f'''SELECT date, {timezone} from ... '''
in PySpark: table = 'schema.my_table' df = spark.sql(f'''select * from {table}''')
2

You can create temporary view in %%sql code, and then reference it from pyspark or scala code like this:

%sql
create temporary view sql_result as
SELECT ...

%scala
var df = spark.sql("SELECT * FROM sql_result")

Comments

1

Since May 2022nd, results of SQL queries in the notebooks are available as _sqldf variable that is corresponding DataFrame object accessible from Python code. See documentation for more details & description of behavior.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.