-
Notifications
You must be signed in to change notification settings - Fork 15
/
extract_eventhubs_json_schema.py
51 lines (35 loc) · 1.14 KB
/
extract_eventhubs_json_schema.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Databricks notebook source
# MAGIC %md ### This notebook reads "body" from first Event Hub message and extracts JSON schema
# COMMAND ----------
import json
connectionString = "<EVENTHUBS_CONNECTIONSTRING>;EntityPath=<EVENTHUB_NAME>"
earliest = {
"offset": "-1",
"seqNo": -1,
"enqueuedTime": None,
"isInclusive": True
}
ehConf = {
"eventhubs.connectionString": connectionString,
"eventhubs.startingPosition": json.dumps(earliest)
}
# COMMAND ----------
rawData = spark.read.format("eventhubs").options(**ehConf).load()
dfBody = rawData.selectExpr("CAST(body AS STRING)")
firstRecordString = dfBody.first()["body"]
firstRecordRDD = sc.parallelize([firstRecordString])
# Create new DataFrame from body's JSON
dfJson = spark.read.json(firstRecordRDD)
# Infer schema from the DataFrame
schema = dfJson.schema.json()
# Store schema in DBFS
schemaFile = "/schema.json"
dbutils.fs.rm(schemaFile)
dbutils.fs.put(schemaFile, schema)
# COMMAND ----------
# MAGIC %fs ls
# COMMAND ----------
from pyspark.sql.types import StructType
with open("/dbfs/schema.json") as jsonData:
schema = StructType.fromJson(json.load(jsonData))
print(schema)