Repository navigation
Expand file tree
/
Copy pathsync_example_avro.py
More file actions
56 lines (47 loc) · 1.56 KB
/
Copy pathsync_example_avro.py
File metadata and controls
56 lines (47 loc) · 1.56 KB
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
52
53
54
55
56
"""
Synchronous Avro ingestion example.
Demonstrates ingesting dict records with the Avro format, including a
`timestamp-millis` logical-type field passed as a `datetime`.
"""
import json
from datetime import datetime, timezone
from zerobus.sdk.sync import TableProperties, ZerobusSdk
# Avro schema with various field types
schema = {
"type": "record",
"name": "SensorReading",
"fields": [
{"name": "device_id", "type": "string"},
{"name": "reading_time", "type": {"type": "long", "logicalType": "timestamp-millis"}},
{"name": "temperature", "type": "double"},
{"name": "count", "type": "long"},
],
}
# Initialize SDK
sdk = ZerobusSdk(
host="https://your-shard.zerobus.region.cloud.databricks.com",
unity_catalog_url="https://your-workspace.cloud.databricks.com",
)
# Create stream with Avro format
table_properties = TableProperties("my_catalog.my_schema.my_table", avro_schema=json.dumps(schema))
stream = sdk.create_stream(
client_id="your-client-id",
client_secret="your-client-secret",
table_properties=table_properties,
)
# Pattern: ingest in a loop, then flush() once
try:
# Ingest dicts (auto-encoded to Avro)
for i in range(10):
record = {
"device_id": f"device-{i}",
"reading_time": datetime.now(timezone.utc),
"temperature": 20.5 + i * 0.1,
"count": i,
}
stream.ingest_record_offset(record)
# Flush all pending records
stream.flush()
print("✓ All records ingested and acknowledged")
finally:
stream.close()