A laptop has 16 GB of memory and the tick archive has 400 GB. Pandas gives up at the first read; a database does not have to, because it never needed the whole table at once. DuckDB can be told how much memory it may use, can spill the overflow to disk, can hand results over in small batches and can read just the folder of a partitioned dataset it needs.
The idea in plain words
Where we are. The previous topic read a plan to see what a query touches. This one acts on it: cap the memory, stream instead of materialise, and lay the files out so a filter on the partition column opens one folder. The capstone then builds a whole research warehouse from these pieces.
Processing data that is larger than the memory available, by keeping only a working set in RAM and moving the rest to and from disk. The query still runs; it trades speed for the ability to finish.
Give DuckDB a budget and a place to spill
SET memory_limit is the budget and SET temp_directory is where operators that run out of room (a big sort, a big join) write their overflow. Without a temp directory an in-memory database has nowhere to spill and fails with an out-of-memory error instead. The limit is reported back in binary units, so 300MB reads as 286.1 MiB.
# A connection with a 300 MB budget that may spill into the folder "spill"limited = limited_connection(300, "spill")print(limited.sql("SELECT current_setting('memory_limit')").fetchall())print(limited.sql("SELECT current_setting('temp_directory')").fetchall())
[('286.1 MiB',)]
[('spill',)]Stream, do not materialise
.df() and .fetchall() build the whole answer in Python memory, which defeats the limit you just set. to_arrow_reader(n) hands the answer over n rows at a time: you reduce each batch, forget it, and ask for the next. Memory stays flat whether the file has thirty thousand rows or three billion.
# Sum the volume column over the whole file, ten thousand rows per batchrows, total, batches = streaming_stats(con, "bars_all.csv", "volume", 10000)print("rows:", rows, "| batches:", batches)print("total volume:", total)print("check against SQL:", con.sql("SELECT sum(volume) FROM bars").fetchall()[0][0] == total)
rows: 33493 | batches: 4 total volume: 3398140608402 check against SQL: True
Partition so a filter opens one folder
PARTITION_BY (symbol) writes one folder per symbol, named symbol=KO. Reading with hive_partitioning = true turns the folder name back into a column, and a WHERE symbol = 'KO' then prunes every other folder before a single byte of them is read. Choose a partition column you filter on and that has few values: thousands of tiny files are slower than one big one.
# Write the lake, then ask for one symbol and count the files that were openedprint(write_partitioned(con, "bars_all.csv", "lake"))rows, files = partition_rows(con, "lake", "KO")print("KO rows:", rows, "| files opened:", files)print("all rows:", con.sql("SELECT count(*) FROM read_parquet('lake/*/*.parquet')").fetchall()[0][0])
['symbol=AAPL', 'symbol=JNJ', 'symbol=JPM', 'symbol=KO', 'symbol=XOM'] KO rows: 6699 | files opened: 1 all rows: 33493
A query that spills can be ten times slower than one that fits, and a limit set too low makes a join thrash. Use the limit to make a job finish on a small machine, not as a tuning knob: if a query spills every day, partition the data, select fewer columns or filter earlier so less reaches the heavy operator.
What the tasks ask
- 1`limited_connection`Connect, then
SET memory_limitandSET temp_directory(usequotefor the path). - 2`streaming_stats`Open
to_arrow_reader(batch_rows)on the CSV and loop: count rows, addpc.sumof each batch, count batches. - 3`write_partitioned` and `partition_rows`
COPY ... (FORMAT parquet, PARTITION_BY (symbol), OVERWRITE_OR_IGNORE), then read back withhive_partitioning = true, filename = trueand filter onsymbol.
symbol, but partition_rows reports five files opened. What is the most likely cause?Lab · what's graded
4 tasks · 100 pts- Limit memory, name a spill folder:
limited_connection25 pts - Stream a file in batches:
streaming_stats25 pts - Partition by symbol:
write_partitioned25 pts - Open only one partition:
partition_rows25 pts