| """
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
| DB_PATH = (Path(__file__).parent / "openrag.db").resolve()
|
|
|
|
|
|
|
| ZVEC_DIR = (Path(__file__).parent / "zvec_db").resolve()
|
|
|
|
|
|
|
|
|
| BATCH_SIZE = 1000
|
|
|
|
|
|
|
| ZVEC_COLLECTION_NAME = os.environ["COLLECTION_NAME"]
|
|
|
|
|
|
|
|
|
|
|
| engine = create_engine(f"sqlite:///{DB_PATH}")
|
| console = Console()
|
| zvec.init(
|
|
|
| memory_limit_mb=8192,
|
| )
|
|
|
|
|
|
|
| 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"))
|
|
|
|
|
| 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.
|
| """
|
|
|
|
|
| return pd.read_sql(
|
| "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).
|
| """
|
|
|
| ids: list[str] = []
|
| embeddings: list[np.ndarray] = []
|
| metadatas: list[dict[str, str | int | float | bool | None]] = []
|
|
|
|
|
|
|
|
|
| for _, row in batch_df.iterrows():
|
|
|
| if row["embedding"] is None:
|
| continue
|
|
|
|
|
|
|
|
|
| vector = np.frombuffer(row["embedding"], dtype=np.float32)
|
| vector = vector / np.linalg.norm(vector)
|
|
|
|
|
| chunk_id: str = str(row["chunk_id"])
|
|
|
|
|
|
|
| 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"]),
|
| "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"]),
|
| }
|
|
|
|
|
| ids.append(chunk_id)
|
| embeddings.append(vector)
|
| metadatas.append(meta)
|
|
|
|
|
| if ids:
|
|
|
| zvec_col.upsert(
|
| [
|
| zvec.Doc(
|
| id=ids[i],
|
| vectors={"embedding": list(embeddings[i])},
|
| fields=metadatas[i],
|
| )
|
| for i in range(len(ids))
|
| ]
|
| )
|
|
|
|
|
| return len(ids)
|
|
|
|
|
|
|
|
|
|
|
| if __name__ == "__main__":
|
|
|
| start_time = time.time()
|
| progress_bar = Progress(
|
| TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
|
| BarColumn(),
|
| MofNCompleteColumn(),
|
| TextColumn("β’"),
|
| TimeElapsedColumn(),
|
| TextColumn("β’"),
|
| TimeRemainingColumn(),
|
| console=console,
|
| )
|
|
|
|
|
|
|
|
|
| shutil.rmtree(ZVEC_DIR, ignore_errors=True)
|
| console.print(f"[bold red]ZVEC directory cleared: {ZVEC_DIR}")
|
|
|
|
|
|
|
|
|
| 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),
|
| ],
|
| )
|
|
|
|
|
| zvec_collection = zvec.create_and_open(path=str(ZVEC_DIR), schema=schema)
|
|
|
| console.print(f"[bold green]ZVECcollection {ZVEC_COLLECTION_NAME} ready.")
|
|
|
|
|
| total = get_total_rows(engine)
|
| console.print(f"[bold orange]Total rows in SQLite: {total:,}")
|
|
|
|
|
|
|
| with progress_bar as p:
|
| task = p.add_task("Transferring to ZVEC...", total=total)
|
| for chunk_df in stream_chunks(engine, BATCH_SIZE):
|
|
|
| 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"
|
| )
|
|
|
|
|
|
|
|
|
|
|