Overview
Data arrives from files, databases and live feeds, each with its own format. Ingestion hides that difference: whatever the source, the rest of the pipeline receives the same thing, a list of records where each record maps column names to values. It hands the records over a chunk at a time, so a source larger than memory can still be processed. It also decides what happens to a broken record: stop at once, or skip it and keep count.
A short history
Ingestion is an engineering practice with no single inventor. It descends from the extract step of extract, transform, load work in data warehousing, which grew through the 1980s and 1990s. Reading in fixed-size chunks is the old answer to data that does not fit in memory, and iterators made it convenient in modern languages. The formats are older than most pipelines: comma-separated files date from early mainframe computing, and SQLite was first released by Richard Hipp in 2000.
How it works
- Choose the
source: csv, jsonl (one JSON object per line), sqlite or stream. - Call
Ingestor.read(location). It returns an iterator, so nothing is loaded until you ask for the next chunk. - Each record is parsed into a dict. For CSV, fields are converted to int, float or None (an empty field) when
infer_typesis on. - A bad record (wrong field count, broken JSON, not an object) raises an error, or is skipped and counted in
stats_whenon_erroris skip. - Good records are gathered into lists of at most
chunk_sizeand yielded one chunk at a time, until the source ends ormax_recordsis reached. - Use
records_to_arrayto turn chosen columns into a float array, with NaN where a value is missing.
Watch out for
- Skipping bad records silently can drop a large share of the data, so always read
stats_["skipped"]after a run and compare it withstats_["read"]. - Type inference looks at one field at a time, so a code such as 007 becomes the number 7 and loses its leading zeros. Turn
infer_typesoff for such columns. read_allloads everything at once, which removes the memory protection that chunking gives.- The stream source waits for the producer to send None as an end marker, so a producer that never sends it leaves the reader waiting.
- This template runs in one process with files, SQLite and a queue. It is a small version of ingestion and has no network sources or database servers.
Use cases
When to use it
As the first step of a pipeline, so later steps do not need to know where the data lives. Read in chunks whenever the source may not fit in memory.
In industry
- Finance
- A bank's risk team loads daily transaction exports from CSV files in chunks, so a file of many gigabytes can be processed on an ordinary machine.
- Web and mobile products
- Application events are written as one JSON object per line. A training job reads the log files chunk by chunk and skips and counts broken lines.
- Internet of things
- Readings from devices arrive as a stream. The same reader interface lets the pipeline consume them in small groups as they arrive.
Choosing it: what must hold
- A source in a supported form: a CSV file, a JSON-lines file, a SQLite database or an in-process stream.
- Records that share a common set of fields, so later steps can treat every chunk alike.
- A decision on bad records: stop at the first one, or skip and count them.
When to choose something else
| If | Use instead |
|---|---|
| The data fits in memory and you only need arrays for training | The dataset and data loader lesson, fed directly from arrays |
| The data is spread over many machines or is too large for one process | A distributed engine such as Apache Spark or a data warehouse query |
| You need to check the content of what was read, not only parse it | Schema-first data validation, run right after ingestion |
Math foundations
Number of chunks
Reading good records in chunks of yields chunks. All are full except possibly the last, which holds the remainder.
Memory held at one time
With chunking the memory in use depends on the chunk size, not on the size of the source. That is why a file of any length can be processed with a fixed budget.
Symbols
- number of good records in the source
- chunk_size, records per chunk
- number of chunks yielded
- average memory used by one record
- memory held by the reader at one time
Worked by hand
A CSV file has 2,500 good rows and chunk_size is 1,000. How many chunks come out, and how large is the last one?
Three chunks: two with 1,000 records and a last one with 500. At no point are more than 1,000 records held by the reader.
Visual example
Loading the example.
Try this
- Press Step a few times and follow one record from the source into the chunk.
- Set on_error to raise and press Run: the read stops at the first bad record.
- Change chunk_size and check the number of chunks against K, the ceiling of N over c.
Code sample
import os, tempfile
from impl import Ingestor, records_to_array
from config import IngestionConfig
path = os.path.join(tempfile.mkdtemp(), "people.csv")
with open(path, "w") as f:
f.write("name,age,height\nAda,36,1.70\nBob,,1.82\n")
ingestor = Ingestor(IngestionConfig(source="csv", chunk_size=1))
for chunk in ingestor.read(path):
print(chunk) # [{'name': 'Ada', 'age': 36, 'height': 1.7}] then Bob with age None
print(records_to_array(ingestor.read_all(path), ["age", "height"])) # [[36, 1.7], [nan, 1.82]]Read the implementation (163 lines)
"""Data ingestion: read records in chunks from a CSV file, a JSON-lines file, a SQLite database or a stream.
Standard library plus NumPy, no network. Every source is turned into the same thing: an iterator of chunks,
each chunk a list of records, each record a dict from column name to value. The rest of a pipeline then does
not care where the data came from. `records_to_array` turns chosen columns into a float array.
"""
from __future__ import annotations
import csv
import json
import queue
import sqlite3
from typing import Iterable, Iterator
import numpy as np
try:
from .config import IngestionConfig
except ImportError: # run from the template's own folder
from config import IngestionConfig
def _infer(text: str):
"""Turn a CSV field into None (empty), int, float or leave it a string."""
if text == "":
return None
for cast in (int, float):
try:
return cast(text)
except ValueError:
pass
return text
def records_to_array(records: list[dict], columns: list[str]) -> np.ndarray:
"""Pick `columns` out of the records as a float array of shape (n_records, n_columns).
A missing key or a None value becomes NaN. A value that is not a number raises ValueError.
"""
out = np.full((len(records), len(columns)), np.nan)
for i, record in enumerate(records):
for j, column in enumerate(columns):
value = record.get(column)
if value is not None:
out[i, j] = float(value)
return out
class Ingestor:
"""Read any supported source as chunks of dict records.
stats_ counts, for the latest `read`: "read" (good records yielded), "skipped" (bad records dropped
when on_error is "skip") and "chunks".
"""
def __init__(self, config: IngestionConfig | None = None) -> None:
self.config = config or IngestionConfig()
self.stats_ = {"read": 0, "skipped": 0, "chunks": 0}
# --------------------------------------------------------------------------------------- per source
def _bad(self, message: str) -> None:
"""Handle one bad record according to on_error."""
if self.config.on_error == "raise":
raise ValueError(message)
self.stats_["skipped"] += 1
def _csv(self, path: str) -> Iterator[dict]:
cfg = self.config
with open(path, newline="", encoding="utf-8") as handle:
reader = csv.reader(handle, delimiter=cfg.delimiter)
header = None
for row in reader:
if not row:
continue # blank line
if header is None:
header = row if cfg.has_header else [f"c{i}" for i in range(len(row))]
if cfg.has_header:
continue
if len(row) != len(header):
self._bad(f"{path} line {reader.line_num}: expected {len(header)} fields, got {len(row)}")
continue
yield dict(zip(header, [_infer(v) for v in row] if cfg.infer_types else row))
def _jsonl(self, path: str) -> Iterator[dict]:
with open(path, encoding="utf-8") as handle:
for number, line in enumerate(handle, start=1):
if not line.strip():
continue
try:
record = json.loads(line)
except json.JSONDecodeError as error:
self._bad(f"{path} line {number}: {error}")
continue
if not isinstance(record, dict):
self._bad(f"{path} line {number}: expected a JSON object, got {type(record).__name__}")
continue
yield record
def _sqlite(self, path: str, query: str | None, params: tuple) -> Iterator[dict]:
if not query:
raise ValueError('source "sqlite" needs a query, for example "SELECT * FROM events"')
connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True) # read-only: ingestion never writes
try:
cursor = connection.execute(query, params)
names = [column[0] for column in cursor.description]
while True:
rows = cursor.fetchmany(self.config.chunk_size)
if not rows:
break
for row in rows:
yield dict(zip(names, row))
finally:
connection.close()
def _stream(self, source) -> Iterator[dict]:
"""A queue.Queue is drained until a None arrives; anything else is simply iterated."""
if isinstance(source, queue.Queue):
items: Iterable = iter(source.get, None)
else:
items = source
for position, record in enumerate(items):
if not isinstance(record, dict):
self._bad(f"stream item {position}: expected a dict, got {type(record).__name__}")
continue
yield record
# ------------------------------------------------------------------------------------------- public
def read(self, location, query: str | None = None, params: tuple = ()) -> Iterator[list[dict]]:
"""Yield chunks (lists of at most chunk_size dict records).
location: a file path for "csv", "jsonl" and "sqlite"; a queue.Queue (ended by a None item) or any
iterable of dicts for "stream".
query: the SELECT statement for "sqlite". `params` are its ? placeholders.
"""
cfg = self.config
self.stats_ = {"read": 0, "skipped": 0, "chunks": 0}
if cfg.source == "csv":
records = self._csv(location)
elif cfg.source == "jsonl":
records = self._jsonl(location)
elif cfg.source == "sqlite":
records = self._sqlite(location, query, params)
else:
records = self._stream(location)
chunk: list[dict] = []
for record in records:
chunk.append(record)
self.stats_["read"] += 1
done = cfg.max_records and self.stats_["read"] >= cfg.max_records
if len(chunk) == cfg.chunk_size or done:
self.stats_["chunks"] += 1
yield chunk
chunk = []
if done:
return
if chunk:
self.stats_["chunks"] += 1
yield chunk
def read_all(self, location, query: str | None = None, params: tuple = ()) -> list[dict]:
"""Every record of the source in one list (for sources known to fit in memory)."""
return [record for chunk in self.read(location, query, params) for record in chunk]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Write a small JSON-lines file with five good lines and one broken line. Read it with Ingestor(IngestionConfig(source="jsonl", chunk_size=2, on_error="skip")), print each chunk and then stats_. Change on_error to raise and note at which line the read stops.
Check on learning
- You can choose a chunk size of 10 or 100,000 for the same file. What do you gain and lose at each end?
A way to think about it
Think about memory on one side and the fixed cost paid once per chunk (a function call, a model call, a database round trip) on the other.
- A nightly export normally has 0.1 percent broken lines and you use skip. One night 30 percent are skipped. The pipeline finishes without an error. What should have happened instead?
A way to think about it
Decide what number you would check and what threshold would make you stop the run. Ask who learns about the problem if nothing checks it.
- Why does
readreturn an iterator instead of a list, and what changes for the code that consumes it?A way to think about it
Ask when the work happens in each case, and what happens if the consumer stops after the first chunk.
- The same column arrives as the integer 3 from SQLite, the text 3 from a CSV with
infer_typesoff, and 3.0 from JSON. Why might a later step break, and where should that be fixed?A way to think about it
Follow one value through
records_to_arrayand through an equality test against a category list. Decide which stage owns the question of types.