使用数据块在 adls gen2 中导入 table 数据并另存为 json 文档

import table data and save as json documents in adls gen2 using databricks

我正在使用下面的代码从 sql 服务器 table 生成 json 结果集。

Powershell:

$InstanceName = "SQLTEST1\ENG_TST1"
$connectionString = "Server=$InstanceName;Database=dbadb;Integrated Security=True;"

$query = "SELECT * FROM dbo.sales"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"

$table.Load($result)

$table | select $table.Columns.ColumnName | ConvertTo-Json

$connection.Close()

能否指导我使用 Azure Databricks 在 Azure Data Lake Storage Gen2 中存储 json 文档。

如果要将文件保存到Azure databricks中的Azure data lake gen2,请参考以下步骤

  1. 创建 Azure Data Lake Storage Gen2 帐户。
az login
az storage account create \
    --name <account-name> \
    --resource-group <group name> \
    --location westus \
    --sku Standard_RAGRS \
    --kind StorageV2 \
    --enable-hierarchical-namespace true
  1. 创建服务主体并将 Storage Blob Data Contributor 分配给 Data Lake Storage Gen2 存储帐户范围内的 sp
az login

az ad sp create-for-rbac -n "MyApp" --role "Storage Blob Data Contributor" \
    --scopes /subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>
  1. 在 Azure Databricks 中创建一个 Spark 集群

  2. 在 Azure 数据块中装载 Azure 数据湖 gen2(python)

configs = {"fs.azure.account.auth.type": "OAuth",
       "fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
       "fs.azure.account.oauth2.client.id": "<appId>",
       "fs.azure.account.oauth2.client.secret": "<clientSecret>",
       "fs.azure.account.oauth2.client.endpoint": "https://login.microsoftonline.com/<tenant>/oauth2/token",
       "fs.azure.createRemoteFileSystemDuringInitialization": "true"}

dbutils.fs.mount(
source = "abfss://<container-name>@<storage-account-name>.dfs.core.windows.net/folder1",
mount_point = "/mnt/flightdata",
extra_configs = configs)
  1. 将 json 保存到 Azure Data Lake gen2
dbutils.fs.put("/mnt/flightdata/<file name>", """
<json string>
""", True)

您可以根据需要使用 df.write.json API 写入任何特定位置。

语法:df.write.json('location where you want to save the json file')

示例:df.write.json("abfss://<file_system>@<storage-account-name>.dfs.core.windows.net/iot_devices.json")

以下是使用 Azure Databricks 将 JSON 文档保存到 Azure Data Lake Gen2 的步骤。

第 1 步: 您可以使用 spark.read.json API 读取 json 文件并创建数据框。

第 2 步: blob 存储位置可以挂载到 databricks dbfs 目录,使用下面文档中的说明

https://docs.microsoft.com/en-us/azure/databricks/data/data-sources/azure/azure-datalake-gen2

Step3:然后使用df.write.jsonAPI写入挂载点,会写入blob存储

更多详情,请参考以下文章:

Azure Databricks – JSON files

示例笔记本: https://docs.microsoft.com/en-us/azure/databricks/_static/notebooks/adls-passthrough-gen2.html