Setup
Let’s first create a virtual environment:If you’re using Jupyter Lab, you’ll need to create a notebook before following the rest of the guide.
Downloading a dataset
We’re going to use one of Jeff Sackmann’s tennis_atp dataset, which contains metadata about players and their rankings over time. Let’s start by downloading the rankings files:Configuring chDB and JupySQL
Next, let’s import thedbapi module for chDB:
atp.chdb directory:
sql magic and create a connection to chDB:
Querying data in CSV files
We’ve downloaded a bunch of files with theatp_rankings prefix.
Let’s use the DESCRIBE clause to understand the schema:
SELECT query directly against these files to see what the data looks like:
REPLACE clause to return the cleaned up ranking_date:
Importing CSV files into chDB
Now we’re going to store the data from these CSV files in a table. The default database doesn’t persist data on disk, so we need to create another database first:rankings whose schema will be derived from the structure of the data in the CSV files:
players based on the content of the CSV file.
We’ll also clean up the dob field so that its a Date32 type.
In ClickHouse, theDatetype only supports dates from 1970 onwards. Since thedobcolumn contains dates from before 1970, we’ll use theDate32type instead.
Querying chDB
Data ingestion is done, now it’s time for the fun part - querying the data! Tennis players receive points based on how well they perform in the tournaments they play. The points for each player over a 52 week rolling period. We’re going to write a query that finds the maximum points accumulate by each player along with their ranking at the time:Saving queries
We can save queries using the--save parameter on the same line as the %%sql magic.
The --no-execute parameter means that query execution will be skipped.
Querying with parameters
We can also use parameters in our queries. Parameters are just normal variables:{{variable}} syntax in our query.
The following query finds the players who had the least number of days between when they first had a ranking in the top 10 and last had a ranking in the top 10: