导入表数据并使用databricks将其另存为json文档在adls gen2中

时间:2020-08-03 18:40:39

标签: powershell azure-databricks azure-data-lake-gen2

我正在使用以下代码从sql server表生成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将json文档存储在Azure Data Lake Storage Gen2中。

2 个答案:

答案 0 :(得分:2)

如果要将文件保存到Azure数据块中的Azure数据湖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 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数据块(python)中安装Azure数据湖gen2

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以使数据湖gen2蔚蓝
dbutils.fs.put("/mnt/flightdata/<file name>", """
<json string>
""", True)

enter image description here

enter image description here

答案 1 :(得分:2)

您可以根据需要使用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

第3步:然后使用df.write.json API写入装载点,该装载点将写入Blob存储空间

有关更多详细信息,请参阅以下文章:

Azure Databricks – JSON files

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

enter image description here