| """
|
| sqlite_qdrant_cloud.py
|
|
|
| Pipeline script to stream embeddings and metadata from a local SQLite database
|
| and upsert them into a Qdrant collection hosted on a remote/cloud Qdrant instance.
|
|
|
| This file preserves the original runtime behavior but adds extensive inline
|
| documentation, module-level descriptions, and detailed docstrings for each
|
| function. The intent is to make the file easier to understand and maintain.
|
|
|
| Ensure qdrant_client is installed in your environment (`pip install qdrant-client`).
|
| """
|
|
|
| import os
|
| import shutil
|
| import time
|
| from pathlib import Path
|
| from typing import Iterator
|
|
|
| import numpy as np
|
| import pandas as pd
|
| from dotenv import load_dotenv
|
| from qdrant_client import QdrantClient, models
|
| from rich.console import Console
|
| from rich.progress import (
|
| BarColumn,
|
| MofNCompleteColumn,
|
| Progress,
|
| TextColumn,
|
| TimeElapsedColumn,
|
| TimeRemainingColumn,
|
| )
|
| from sqlalchemy import create_engine, text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| load_dotenv()
|
|
|
|
|
|
|
|
|
| DB_PATH = (Path(__file__).parent / "openrag.db").resolve()
|
|
|
|
|
|
|
|
|
| engine = create_engine(f"sqlite:///{DB_PATH}")
|
|
|
|
|
|
|
|
|
|
|
| QDRANT_COLLECTION_NAME = os.environ["COLLECTION_NAME"]
|
|
|
| console = Console()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| if "SSL_CERT_FILE" not in os.environ:
|
| os.environ["SSL_CERT_FILE"] = "cisco_umbrella_root_ca.pem"
|
| if "REQUESTS_CA_BUNDLE" not in os.environ:
|
| os.environ["REQUESTS_CA_BUNDLE"] = "cisco_umbrella_root_ca.pem"
|
|
|
|
|
|
|
|
|
|
|
| def get_total_rows(eng) -> int:
|
| """
|
| Return the total row count for the `embeddingcontent` table.
|
|
|
| This function executes a simple and fast `SELECT COUNT(*)` query. It is
|
| used to provide an accurate total to the progress bar without loading
|
| all rows into memory.
|
|
|
| Parameters
|
| ----------
|
| eng:
|
| A SQLAlchemy Engine connected to the SQLite DB.
|
|
|
| Returns
|
| -------
|
| int
|
| The number of rows in the `embeddingcontent` table.
|
|
|
| Notes
|
| -----
|
| - This intentionally does not fetch any row data; it only returns the
|
| scalar count.
|
| - If the table does not exist or the DB is inaccessible, SQLAlchemy will
|
| raise an exception — callers should be prepared to handle that.
|
| """
|
| with eng.connect() as con:
|
| result = con.execute(text("SELECT COUNT(*) FROM embeddingcontent"))
|
|
|
| return result.scalar_one()
|
|
|
|
|
| def stream_chunks(eng, batch_size: int) -> Iterator[pd.DataFrame]:
|
| """
|
| Stream the `embeddingcontent` table in fixed-size DataFrame chunks.
|
|
|
| This wrapper returns a generator/iterator of pandas DataFrame objects by
|
| delegating to `pd.read_sql(..., chunksize=batch_size)`. Using `chunksize`
|
| ensures that only one batch (one DataFrame) is materialized at a time,
|
| which keeps memory usage bounded and predictable even for very large
|
| SQLite files.
|
|
|
| Parameters
|
| ----------
|
| eng:
|
| A SQLAlchemy Engine connected to the SQLite DB.
|
| batch_size:
|
| Number of rows to fetch per yielded DataFrame.
|
|
|
| Returns
|
| -------
|
| Iterator[pd.DataFrame]
|
| An iterator which yields DataFrame chunks in ascending `chunk_id`
|
| order. Each yielded DataFrame contains the columns present in the
|
| `embeddingcontent` table, including the binary `embedding` column.
|
|
|
| Notes
|
| -----
|
| - The returned iterator may be backed by a SQL cursor depending on the
|
| pandas/sqlalchemy runtime; this is the core mechanism that avoids
|
| loading the full table into memory.
|
| - The `# type: ignore[return-value]` is present on the return to bypass a
|
| static typing mismatch between pandas' dynamic iterator return and the
|
| static function signature.
|
| """
|
| return pd.read_sql(
|
| "SELECT * FROM embeddingcontent ORDER BY chunk_id",
|
| eng,
|
| chunksize=batch_size,
|
| )
|
|
|
|
|
|
|
|
|
|
|
| def insert_to_qdrant(
|
| qdrant_client: QdrantClient, collection_name: str, batch_df: pd.DataFrame
|
| ):
|
| """
|
| Insert a batch of rows into a Qdrant collection.
|
|
|
| This function converts rows from the provided DataFrame into Qdrant
|
| `PointStruct` objects and performs a single `upsert` call for the entire
|
| batch for efficiency.
|
|
|
| Expected DataFrame columns
|
| --------------------------
|
| - chunk_id: primary key for the chunk (kept as-is, Qdrant accepts str/int)
|
| - embedding: binary blob containing float32 bytes for the vector
|
| - product_id, content_type, heading_h1, heading_h2, heading_h3,
|
| section_heading, heading_level, chunk_text, title, date_published, url,
|
| program_name: metadata fields that will be placed in the Qdrant payload
|
|
|
| Parameters
|
| ----------
|
| qdrant_client:
|
| An initialized `qdrant_client.QdrantClient` instance connected to the
|
| target Qdrant instance.
|
| collection_name:
|
| The target Qdrant collection name to upsert into.
|
| batch_df:
|
| A pandas DataFrame representing a chunk of rows obtained from the
|
| `embeddingcontent` table.
|
|
|
| Behavior and important notes
|
| ----------------------------
|
| - Rows with NULL `embedding` are skipped (no vector to store).
|
| - The `embedding` binary blob is converted to a list of floats using
|
| `np.frombuffer(..., dtype=np.float32)` and stored directly in the point
|
| (the Qdrant collection uses a single unnamed vector config).
|
| - Metadata is written into the `payload` dict of each point.
|
| - Any additional fields present in the DataFrame could be added to the
|
| payload if desired; the current implementation uses a curated list.
|
| - Qdrant can accept integer or string IDs; this script uses `row["chunk_id"]`
|
| as provided by the database.
|
| """
|
| points = []
|
|
|
|
|
|
|
| for _, row in batch_df.iterrows():
|
|
|
| if row["embedding"] is None:
|
| continue
|
|
|
|
|
|
|
| point = models.PointStruct(
|
| id=row["chunk_id"],
|
| vector=list(np.frombuffer(row["embedding"], dtype=np.float32)),
|
| payload={
|
|
|
|
|
|
|
| "product_id": row["product_id"],
|
| "content_type": row["content_type"],
|
| "heading_h1": row["heading_h1"],
|
| "heading_h2": row["heading_h2"],
|
| "heading_h3": row["heading_h3"],
|
| "heading_level": row["heading_level"],
|
| "page_start": row["page_start"],
|
| "page_end": row["page_end"],
|
| "chunk_text": row["chunk_text"],
|
| "title": row["title"],
|
| "date_published": row["date_published"],
|
| "url": row["url"],
|
| "program_name": row["program_name"],
|
| "abstract": row["abstract"],
|
| "keywords": row["keywords"],
|
| },
|
| )
|
| points.append(point)
|
|
|
|
|
|
|
| qdrant_client.upsert(collection_name=collection_name, points=points)
|
|
|
|
|
|
|
|
|
|
|
| def create_collection(q_cl: QdrantClient):
|
| """
|
| Create a Qdrant collection configured for the project's embeddings.
|
|
|
| This function:
|
| - Deletes the collection if it already exists (purging prior data).
|
| This behavior ensures a fresh collection is created on each run.
|
| - Creates the collection with a single unnamed vector config (1024-dim,
|
| COSINE distance). Vectors are stored on disk for large collections.
|
| - Applies binary quantization to reduce vector storage size.
|
| - Tuned HNSW and optimizer configs for efficient ingestion of large
|
| datasets (see reference for design rationale).
|
|
|
| Parameters
|
| ----------
|
| q_cl:
|
| An instance of `qdrant_client.QdrantClient` already connected to the
|
| target Qdrant host.
|
|
|
| Notes
|
| -----
|
| - Deleting and recreating a collection is destructive. If you prefer to
|
| append to an existing collection, modify this function to skip deletion.
|
| - Vector config: COSINE distance, 1024 dimensions, on-disk storage.
|
| - Quantization: Binary quantization (reduces storage by ~32x for binary-
|
| compatible vectors). `always_ram=True` keeps quantized lookup tables
|
| in RAM for fast decoding.
|
| - HNSW: m=6 (lower branching factor for memory efficiency),
|
| ef_construct=200, on-disk=False (index graph stays in RAM).
|
| - Max segment size: 5,000,000 vectors per segment for faster search.
|
| Reference
|
| ----------
|
| - https://qdrant.tech/course/essentials/day-4/large-scale-ingestion/
|
| """
|
|
|
| if q_cl.collection_exists(QDRANT_COLLECTION_NAME):
|
| q_cl.delete_collection(QDRANT_COLLECTION_NAME)
|
|
|
|
|
|
|
| q_cl.create_collection(
|
| collection_name=QDRANT_COLLECTION_NAME,
|
| vectors_config=models.VectorParams(
|
| size=int(os.getenv("DENSE_VECTOR_DIM", 1024)),
|
| distance=models.Distance.COSINE,
|
| on_disk=True,
|
| ),
|
| quantization_config=models.BinaryQuantization(
|
| binary=models.BinaryQuantizationConfig(
|
| always_ram=True,
|
| )
|
| ),
|
| optimizers_config=models.OptimizersConfigDiff(
|
| max_segment_size=5_000_00,
|
| ),
|
| hnsw_config=models.HnswConfigDiff(
|
| m=6,
|
| ef_construct=200,
|
| on_disk=False,
|
| ),
|
| )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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((Path(__file__).parent / "qdrant_db").resolve(), ignore_errors=True)
|
|
|
|
|
|
|
| qdrant_cloud = QdrantClient(
|
| url=os.environ["QDRANT_BASE_URL"],
|
| https="https" in os.environ["QDRANT_BASE_URL"],
|
| prefer_grpc=False,
|
| timeout=3000,
|
| )
|
|
|
|
|
| create_collection(qdrant_cloud)
|
|
|
|
|
|
|
| console.print(
|
| f"Number of Existing Points: {qdrant_cloud.count(collection_name=QDRANT_COLLECTION_NAME, exact=True).count}"
|
| )
|
|
|
|
|
| BATCH_SIZE = 1000
|
|
|
|
|
|
|
| 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 Qdrant...", total=total)
|
| for chunk_df in stream_chunks(engine, BATCH_SIZE):
|
| insert_to_qdrant(
|
| collection_name=QDRANT_COLLECTION_NAME,
|
| batch_df=chunk_df,
|
| qdrant_client=qdrant_cloud,
|
| )
|
|
|
| p.advance(task, len(chunk_df))
|
|
|
|
|
| console.print(
|
| f"[bold green]Done. Qdrant collection count: {qdrant_cloud.count(collection_name=QDRANT_COLLECTION_NAME, exact=True).count}"
|
| )
|
| console.print(
|
| f"[bold green]Total Elapsed Time : {time.time() - start_time:.2f} seconds"
|
| )
|
|
|