讀寫文字檔

text 格式會將文字檔中的每一行讀取為 DataFrame 中的一個資料列,且該 DataFrame 只有一個名為 value、型別為 StringType 的欄位。 Azure Databricks 使用者常用它來進行日誌解析、在進一步處理前擷取原始資料,或任何需要逐行存取檔案內容的工作流程。 Azure Databricks 支援 Apache Spark 的讀寫文字檔,包括寫入壓縮。

先決條件

Azure Databricks 使用文字檔不需要額外設定。 不過,要串流文字檔,你需要 Auto Loader

選項

使用 DataFrameReaderDataFrameWriter.option().options() 方法來設定文字資料來源。 完整支援選項清單,請參見 DataFrameReader 文字選項DataFrameWriter 文字選項

Usage

以下範例使用 Wanderbricks 資料集 示範使用 Spark DataFrame API 與 SQL 讀寫文字檔。

使用 SQL 讀取文字檔案

若要查詢文字檔而不註冊資料表,請使用 read_files。 Unity Catalog 對外部位置的權限會自動套用。

SELECT * FROM read_files(
  '/Volumes/<catalog>/<schema>/<volume>/review_comments',
  format => 'text'
)

讀寫文字檔

text 格式需要一個只有一 StringType 欄的資料框架。 以下範例將 Wanderbricks 評論寫成文字檔,然後再讀回來。

Python

from pyspark.sql.functions import col

# Write wanderbricks review comments as a text file
df = spark.read.table("samples.wanderbricks.reviews").select(col("comment").alias("value"))
df.write.format("text").save("/Volumes/<catalog>/<schema>/<volume>/review_comments")

# Read a text file — each line becomes a row in the "value" column
df = spark.read.format("text").load("/Volumes/<catalog>/<schema>/<volume>/review_comments")
display(df)

Scala

import org.apache.spark.sql.functions.col

// Write wanderbricks review comments as a text file
val df = spark.read.table("samples.wanderbricks.reviews").select(col("comment").alias("value"))
df.write.format("text").save("/Volumes/<catalog>/<schema>/<volume>/review_comments")

// Read a text file — each line becomes a row in the "value" column
val text = spark.read.format("text").load("/Volumes/<catalog>/<schema>/<volume>/review_comments")
text.show()

其他資源

  • 讀寫 CSV 檔案:如果你的文字資料是分隔或表格,CSV 提供結構化解析、結構推論、標頭支援及可設定分隔符。