Dispatch stream of events to multiple tables in DuckDB
This is a practical example of how to process GitHub events from the dlt repository, such as issues or pull request creation, comments addition, etc. We'll use the GitHub API to fetch the events and duckdb as a destination. Each event type will be sent to a separate table in DuckDB.
Setup
- Install dlt with duckdb support:
pip install "dlt[duckdb]"
- Create a new a new file
github_events_dispatch.py
and paste the following code:
import dlt
from dlt.sources.helpers import requests
@dlt.resource(
primary_key="id",
table_name=lambda i: i["type"],
write_disposition="append",
)
def repo_events(last_created_at=dlt.sources.incremental("created_at")):
url = "https://api.github.com/repos/dlt-hub/dlt/events?per_page=100"
while True:
response = requests.get(url)
response.raise_for_status()
yield response.json()
# stop requesting pages if the last element was already older than
# the initial value
# note: incremental will skip those items anyway, we just do not
# want to use the api limits
if last_created_at.start_out_of_range:
break
# get next page
if "next" not in response.links:
break
url = response.links["next"]["url"]
pipeline = dlt.pipeline(
pipeline_name="github_events",
destination="duckdb",
dataset_name="github_events_data",
)
load_info = pipeline.run(repo_events)
row_counts = pipeline.last_trace.last_normalize_info
print(row_counts)
print("------")
print(load_info)
In the code above we define a resource repo_events
that fetches events from the GitHub API.
Events content never changes so we can use append
write disposition and track new events using created_at
field.
We name the tables using a function that receives an event data and returns table name: table_name=lambda i: i["type"]
- Now run the script:
python github_events_dispatch.py
- Peek at created tables:
dlt pipeline -v github_events info
dlt pipeline github_events trace
- And preview the data:
dlt pipeline -v github_events show
Some of the events produce tables with really many child tables. You can control the level of table nesting with a decorator.
Another fun Colab Demo - we analyze reactions on duckdb repo!
Learn more:
- Change nesting of the tables with a decorator.