簡體   English   中英

如何將 spark 數據框轉換為 SQL 查詢?

[英]How to convert spark dataframe into SQL query?

現在我在 spark 數據框中獲得了數據,我想轉換回 SQL 進行一些分析。 有誰知道我該怎么做? 像 df.to_sql(...)?

謝謝!

您可以使用explain運算符,請參閱此鏈接

試試這個:

df.write.option('header','true').saveAsTable("my_sql_table")

然后,您可以使用 SQL 查詢 my_sql_table。

您可以使用 Spark-sql 將 DataFrame 作為 SQL 處理。

val df = Seq(("Edward", 1, 1000,"me1@example.com"),
                ("Michal",2,15000,"me1@example.com"),
                ("Steve",3,25000,"you@example.com"),
                ("Jordan",4,40000, "me1@example.com")).
      toDF("Name", "ID", "Salary","MailId")
OR
val df = spark.read.json("examples/src/main/resources/employee.json")

// Displays the content of the DataFrame to stdout
df.show()
+------+---+------+---------------+
|  Name| ID|Salary|         MailId|
+------+---+------+---------------+
|Edward|  1|  1000|me1@example.com|
|Michal|  2| 15000|me1@example.com|
| Steve|  3| 25000|you@example.com|
|Jordan|  4| 40000|me1@example.com|
+------+---+------+---------------+

使用 $-notation 需要此導入

import spark.implicits._

// Print the schema in a tree format
df.printSchema()

// Select only the "name" column
df.select("name").show()

// Select employees whose salary > 15000
df.filter($"Salary" > 15000).show()

甚至 SparkSession 上的 sql 函數也使應用程序能夠以編程方式運行 SQL 查詢並將結果作為數據幀返回。

// Register the DataFrame as a SQL temporary view
df.createOrReplaceTempView("employee")

    val sqlDF = spark.sql("SELECT * FROM employee")
    sqlDF.show()

+------+---+------+---------------+
    |  Name| ID|Salary|         MailId|
    +------+---+------+---------------+
    |Edward|  1|  1000|me1@example.com|
    |Michal|  2| 15000|me1@example.com|
    | Steve|  3| 25000|you@example.com|
    |Jordan|  4| 40000|me1@example.com|
    +------+---+------+---------------+

Spark SQL 中的臨時視圖是會話范圍的,如果創建它的會話終止,它就會消失。 如果您希望有一個在所有會話之間共享的臨時視圖並在 Spark 應用程序終止之前保持活動狀態,您可以創建一個全局臨時視圖。

// Register the DataFrame as a global temporary view
df.createGlobalTempView("employee")

// Global temporary view is tied to a system preserved database `global_temp`
spark.sql("SELECT * FROM global_temp.employee").show()

+------+---+------+---------------+
|  Name| ID|Salary|         MailId|
+------+---+------+---------------+
|Edward|  1|  1000|me1@example.com|
|Michal|  2| 15000|me1@example.com|
| Steve|  3| 25000|you@example.com|
|Jordan|  4| 40000|me1@example.com|
+------+---+------+---------------+

請參閱 Spark 文檔。

https://spark.apache.org/docs/2.3.0/sql-programming-guide.html

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM