joonleeEPRI's picture
Upload 13 files
8fa8ded verified
Raw
History Blame
14.2 kB
"""
SQLite β†’ ZVEC Pipeline Script
This module reads chunk embeddings and associated metadata from a local
SQLite database and upserts them into a persistent local ZVEC collection.
It is designed to operate in a memory-efficient streaming fashion so that
very large SQLite tables (multi-GB) can be migrated without exhausting
system RAM.
Ensure zvec is installed in your environment (`pip install zvec`).
Key design points:
- Memory-safety: Uses `pd.read_sql(..., chunksize=...)` to stream rows in
small batches instead of loading the entire table into memory.
- ZVEC constraints: Metadata/fields are stored as strings because ZVEC
field schemas require string-typed values.
- IDs are coerced to strings because ZVEC requires string IDs.
- `chunk_text` is stored as a ZVEC field so it can be used for
text-based retrieval alongside vector search.
- Progress reporting: A cheap COUNT(*) query obtains the total number
of rows to feed the progress bar/ETA without materializing row data.
Usage:
python sqlite_zvec.py
Note: This script intentionally clears the ZVEC directory at the start so
that each run produces a fresh collection. If you want to append to an
existing collection, remove the `shutil.rmtree(ZVEC_DIR, ...)` call in the
__main__ block.
"""
import os
import shutil
import time
from pathlib import Path
from typing import Iterator
import numpy as np
import pandas as pd
import zvec
from dotenv import load_dotenv
from rich.console import Console
from rich.progress import (
BarColumn,
MofNCompleteColumn,
Progress,
TextColumn,
TimeElapsedColumn,
TimeRemainingColumn,
)
from sqlalchemy import Engine, create_engine, text
load_dotenv()
# ── Constants ─────────────────────────────────────────────────────────────────
# Location of the local SQLite DB file. This script expects a table named
# `embeddingcontent` containing one row per chunk with a `bge_dense_embedding`
# binary blob column that stores the float32 embedding bytes.
DB_PATH = (Path(__file__).parent / "openrag.db").resolve()
# Persistent local ZVEC storage directory. This folder gets deleted
# at the start of the script to ensure a clean persistent collection.
ZVEC_DIR = (Path(__file__).parent / "zvec_db").resolve()
# How many rows to fetch and insert into ZVEC in a single batch.
# This is intentionally modest to keep memory usage low. Adjust only if
# you know you have plenty of RAM and want higher throughput.
BATCH_SIZE = 1000
# Name of the ZVEC collection used for this project. Kept as a constant
# so other scripts can refer to the same name if needed.
ZVEC_COLLECTION_NAME = os.environ["COLLECTION_NAME"]
# ── Database engine ───────────────────────────────────────────────────────────
# Create a SQLAlchemy engine that points to the local SQLite database.
# We use SQLAlchemy to run the COUNT query and to provide the connection
# object to pandas.read_sql for streaming.
engine = create_engine(f"sqlite:///{DB_PATH}")
console = Console()
zvec.init(
# Resource limits
memory_limit_mb=8192, # 8GB memory limit
)
# ── Helpers ───────────────────────────────────────────────────────────────────
def _to_str_or_none(value) -> str | None:
"""Convert a value to string, treating NaN/None as None."""
if value is None or (isinstance(value, float) and np.isnan(value)):
return None
return str(value)
def get_total_rows(eng: Engine) -> int:
"""
Return the total number of rows in the `embeddingcontent` table.
This function performs a cheap SQL COUNT query. We use this value to
initialize an accurate progress bar without needing to load any row
data into memory first.
Parameters
----------
eng:
A SQLAlchemy Engine connected to the SQLite database.
Returns
-------
int
The total number of rows in the `embeddingcontent` table.
Raises
------
Any exception that SQLAlchemy/SQLite surfaces for an invalid query or
broken connection (left to the caller to handle or let propagate).
"""
with eng.connect() as con:
result = con.execute(text("SELECT COUNT(*) FROM embeddingcontent"))
# scalar_one() will raise if the query returns no rows; in this
# context we expect exactly one scalar result (the count).
return result.scalar_one()
def stream_chunks(eng: Engine, batch_size: int) -> Iterator[pd.DataFrame]:
"""
Stream the embeddingcontent table as an iterator of DataFrame chunks.
Uses `pd.read_sql(..., chunksize=batch_size)` which under the hood
uses a SQL cursor-like streaming approach. Only one chunk is
materialized at a time, keeping peak RAM usage proportional to the
batch size instead of the full table size.
Parameters
----------
eng:
A SQLAlchemy Engine to read from.
batch_size:
Number of rows per yielded DataFrame chunk.
Returns
-------
Iterator[pd.DataFrame]
An iterator that yields DataFrame objects containing up to
`batch_size` rows each. Each DataFrame includes the binary
`bge_dense_embedding` column which is decoded later.
"""
# We use `# type: ignore[return-value]` where pandas typing might not match
# exactly what static checkers expect for an Iterator return type.
return pd.read_sql( # type: ignore[return-value]
"SELECT * FROM embeddingcontent ORDER BY chunk_id",
eng,
chunksize=batch_size,
)
def insert_to_zvec(
zvec_col,
batch_df: pd.DataFrame,
) -> int:
"""
Insert a single batch of rows (DataFrame) into the given ZVEC collection.
Responsibilities & behavior:
- Decode the binary `embedding` column (stored as raw bytes of
float32 values) into a NumPy array using `np.frombuffer(..., dtype=np.float32)`.
- Convert `chunk_id` to a string
- Build the field schema.
- Use `zvec.Doc` objects and call `zvec_col.upsert()` once per batch
for efficiency.
Important implementation notes:
- If a row does not contain an embedding (`embedding` is NULL), that
row is skipped.
Parameters
----------
zvec_col:
An open `zvec.Collection` instance to upsert into.
batch_df:
A pandas DataFrame containing up to `BATCH_SIZE` rows read from
the `embeddingcontent` table. The DataFrame must contain the
`embedding` binary column and the metadata columns used below.
Returns
-------
int
The number of records that were inserted (i.e., rows that had a
non-null embedding and were upserted).
"""
# Lists to accumulate batch payloads for a single upsert call.
ids: list[str] = []
embeddings: list[np.ndarray] = []
metadatas: list[dict[str, str | int | float | bool | None]] = []
# Iterate rows in the DataFrame. We use pandas' `.iterrows()` which is
# acceptable here because batch sizes are small (BATCH_SIZE). Larger
# batches could use a vectorized approach, but that would consume more RAM.
for _, row in batch_df.iterrows():
# Skip rows with no embedding stored.
if row["embedding"] is None:
continue
# The `embedding` column is stored as a binary blob of float32 values.
# `np.frombuffer` creates a NumPy view directly on the bytes without
# an additional copy if possible. This produces a 1-D ndarray.
vector = np.frombuffer(row["embedding"], dtype=np.float32)
vector = vector / np.linalg.norm(vector)
# ZVEC requires string IDs.
chunk_id: str = str(row["chunk_id"])
# Prepare field values with types safe for ZVEC. We only include a
# curated set of fields here β€” change this mapping if you need more.
meta: dict[str, str | int | float | bool | None] = {
"product_id": row["product_id"],
"content_type": row["content_type"],
"heading_h1": _to_str_or_none(row["heading_h1"]), # type:ignore
"heading_h2": _to_str_or_none(row["heading_h2"]),
"heading_h3": _to_str_or_none(row["heading_h3"]),
"heading_level": row["heading_level"],
"page_start": row["page_start"],
"page_end": row["page_end"],
"chunk_text": row["chunk_text"],
"title": _to_str_or_none(row["title"]),
"date_published": _to_str_or_none(row["date_published"]),
"url": _to_str_or_none(row["url"]),
"program_name": _to_str_or_none(row["program_name"]),
"abstract": _to_str_or_none(row["abstract"]),
"keywords": _to_str_or_none(row["keywords"]),
}
# Accumulate values for a single batched upsert call.
ids.append(chunk_id)
embeddings.append(vector)
metadatas.append(meta)
# If we collected any valid ids/embeddings, send them to ZVEC in one call.
if ids:
# Build `zvec.Doc` objects for each record and upsert them.
zvec_col.upsert(
[
zvec.Doc(
id=ids[i],
vectors={"embedding": list(embeddings[i])},
fields=metadatas[i],
)
for i in range(len(ids))
]
)
# Return how many points we actually attempted to insert.
return len(ids)
# ── Entry point ───────────────────────────────────────────────────────────────
if __name__ == "__main__":
# Configure a compact, informative progress bar using Rich.
start_time = time.time()
progress_bar = Progress(
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
BarColumn(),
MofNCompleteColumn(),
TextColumn("β€’"),
TimeElapsedColumn(),
TextColumn("β€’"),
TimeRemainingColumn(),
console=console,
)
# WARNING: This deletes any existing ZVEC data at ZVEC_DIR. This keeps
# runs reproducible (fresh index/storage), but if you want to preserve
# an existing collection, remove or comment out the next line.
shutil.rmtree(ZVEC_DIR, ignore_errors=True)
console.print(f"[bold red]ZVEC directory cleared: {ZVEC_DIR}")
# Define the ZVEC collection schema with vector fields and metadata fields.
# FP16 vectors are used to save storage; the dimension must match the
# embedding model (1024 for this dataset).
schema = zvec.CollectionSchema(
name=ZVEC_COLLECTION_NAME,
vectors=zvec.VectorSchema(
name="embedding",
data_type=zvec.DataType.VECTOR_FP32,
dimension=int(os.getenv("DENSE_VECTOR_DIM", 1024)),
index_param=zvec.HnswIndexParam(
metric_type=zvec.MetricType.COSINE, ef_construction=700, m=64
),
),
fields=[
zvec.FieldSchema("product_id", zvec.DataType.STRING, nullable=False),
zvec.FieldSchema("content_type", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("heading_h1", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("heading_h2", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("heading_h3", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("heading_level", zvec.DataType.INT64, nullable=False),
zvec.FieldSchema("page_start", zvec.DataType.INT64, nullable=False),
zvec.FieldSchema("page_end", zvec.DataType.INT64, nullable=False),
zvec.FieldSchema("chunk_text", zvec.DataType.STRING, nullable=False),
zvec.FieldSchema("title", zvec.DataType.STRING, nullable=False),
zvec.FieldSchema("date_published", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("url", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("program_name", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("abstract", zvec.DataType.STRING, nullable=True),
zvec.FieldSchema("keywords", zvec.DataType.STRING, nullable=True),
],
)
# Create collection
zvec_collection = zvec.create_and_open(path=str(ZVEC_DIR), schema=schema)
console.print(f"[bold green]ZVECcollection {ZVEC_COLLECTION_NAME} ready.")
# Determine how many rows we will process so the progress bar has a total.
total = get_total_rows(engine)
console.print(f"[bold orange]Total rows in SQLite: {total:,}")
# Stream the table in batches and upsert into ZVEC. The loop keeps
# only one batch in memory at any time, preventing memory pressure.
with progress_bar as p:
task = p.add_task("Transferring to ZVEC...", total=total)
for chunk_df in stream_chunks(engine, BATCH_SIZE):
# Insert the current chunk into ZVEC and advance the progress bar.
insert_to_zvec(zvec_col=zvec_collection, batch_df=chunk_df)
p.advance(task, len(chunk_df))
zvec_collection.optimize()
console.print(zvec_collection.stats)
console.print(
f"[bold green]Total Elapsed Time : {time.time() - start_time:.2f} seconds"
)
# Report final collection size. Note: depending on how ZVEC counts,
# this number may differ slightly from the number of rows processed
# if some rows were skipped because they had no embedding.
# print(f"Done. ZVEC collection count: {zvec_collection.count():,}")