EPRI-Public-Reports-RAG-Database / sqlite_qdrant_cloud.py
joonleeEPRI's picture
Upload 13 files
8fa8ded verified
Raw
History Blame
16.2 kB
"""
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
# --------------------------------------------------------------------------------
# Environment and configuration
# --------------------------------------------------------------------------------
#
# The script reads configuration from the environment (optionally from a .env
# file placed next to the repository). The important variables are:
#
# - QDRANT_BASE_URL: Base URL for the Qdrant instance (including host:port)
# - Optionally any requests/SSL cert override variables if needed by the network
#
# We call `load_dotenv()` to provide local convenience for development; in CI or
# production environments you may provide env vars through normal OS mechanisms.
#
load_dotenv() # Load environment variables from .env file (if present)
# Path to the local SQLite database that stores the chunk-level embedding table.
# The table expected by this script is `embeddingcontent` and contains one row
# per chunk, with an `embedding` column (binary blob of float32 bytes).
DB_PATH = (Path(__file__).parent / "openrag.db").resolve()
# Create a SQLAlchemy engine pointing to that SQLite database. We use the engine
# both for an initial COUNT(*) query (to drive the progress bar) and as the
# connection object passed into pandas' `read_sql(..., chunksize=...)`.
engine = create_engine(f"sqlite:///{DB_PATH}")
# Constants for the Qdrant collection and the named-vector key.
# These must match how the vectors were originally named if migrating or
# interoperating with other systems.
# Name of the Qdrant collection to search
QDRANT_COLLECTION_NAME = os.environ["COLLECTION_NAME"]
console = Console()
# --------------------------------------------------------------------------------
# SSL / CA bundle environment defaults
# --------------------------------------------------------------------------------
#
# Some environments require explicit cert bundle configuration. These defaults
# are present to help avoid requests/urllib SSL issues when the environment
# doesn't already provide these variables. They point to a repo-local PEM file
# in the original project; adjust or remove as needed for your deployment.
#
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"
# --------------------------------------------------------------------------------
# Database streaming helpers
# --------------------------------------------------------------------------------
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"))
# scalar_one() is used to ensure we get exactly one scalar result back.
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( # type: ignore[return-value]
"SELECT * FROM embeddingcontent ORDER BY chunk_id",
eng,
chunksize=batch_size,
)
# --------------------------------------------------------------------------------
# Qdrant insertion helper
# --------------------------------------------------------------------------------
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 = []
# Iterate through rows in the batch DataFrame. Using `.iterrows()` is
# acceptable here because we intentionally keep batch sizes modest.
for _, row in batch_df.iterrows():
# Skip rows that have no embedding stored.
if row["embedding"] is None:
continue
# Convert raw float32 bytes -> Python list of floats for Qdrant.
# `np.frombuffer` avoids an extra copy when possible.
point = models.PointStruct(
id=row["chunk_id"],
vector=list(np.frombuffer(row["embedding"], dtype=np.float32)),
payload={
# The following payload fields mirror the embeddingcontent
# schema. They are included so that when searching in Qdrant,
# the payload can be returned along with nearest neighbor hits.
"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)
# Perform a batch upsert for the entire points list. Upserting in batches
# is much faster than individual point inserts.
qdrant_client.upsert(collection_name=collection_name, points=points)
# --------------------------------------------------------------------------------
# Qdrant collection creation helper
# --------------------------------------------------------------------------------
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 the collection already exists, remove it so we start fresh.
if q_cl.collection_exists(QDRANT_COLLECTION_NAME):
q_cl.delete_collection(QDRANT_COLLECTION_NAME)
# Create the collection with a named vector configuration. This sample uses
# `Distance.COSINE` as the similarity metric and specific HNSW tuning params.
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, # Keep quantized vectors in RAM
)
),
optimizers_config=models.OptimizersConfigDiff(
max_segment_size=5_000_00, # Create larger segments for faster search
),
hnsw_config=models.HnswConfigDiff(
m=6, # Lower m to reduce memory usage
ef_construct=200,
on_disk=False, # Keep the HNSW index graph in RAM
),
)
# Note: quantization is set via BinaryQuantization in the collection
# creation above (not disabled). The original "disabled" comment has been
# updated to reflect the actual binary quantization that is applied.
# --------------------------------------------------------------------------------
# Main entrypoint
# --------------------------------------------------------------------------------
if __name__ == "__main__":
# Configure a progress bar with several useful columns:
# - percentage, a visual bar, completed/total count, elapsed, and ETA.
start_time = time.time()
progress_bar = Progress(
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
BarColumn(),
MofNCompleteColumn(),
TextColumn("•"),
TimeElapsedColumn(),
TextColumn("•"),
TimeRemainingColumn(),
console=console,
)
# The original script removed a local `qdrant_db` directory; this legacy
# cleanup is preserved for parity. It is safe to leave but has no effect
# on cloud-hosted Qdrant unless your local environment also stored data.
shutil.rmtree((Path(__file__).parent / "qdrant_db").resolve(), ignore_errors=True)
# Build a Qdrant client connected to the configured base URL. The
# environment variable QDRANT_BASE_URL must be set (or the script will raise).
qdrant_cloud = QdrantClient(
url=os.environ["QDRANT_BASE_URL"],
https="https" in os.environ["QDRANT_BASE_URL"],
prefer_grpc=False,
timeout=3000,
)
# Create the collection (this will delete & recreate if it already exists).
create_collection(qdrant_cloud)
# Print the current number of points in the (newly-created) collection.
# For a fresh collection this should normally be zero.
console.print(
f"Number of Existing Points: {qdrant_cloud.count(collection_name=QDRANT_COLLECTION_NAME, exact=True).count}"
)
# Batch size used when streaming rows and inserting into Qdrant.
BATCH_SIZE = 1000
# First obtain a count of how many rows we will process so the progress bar
# has an accurate total and ETA. This is a cheap SQL query.
total = get_total_rows(engine)
console.print(f"[bold orange]Total rows in SQLite: {total:,}")
# Stream in batches and upsert each batch into Qdrant.
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,
)
# Advance the progress bar by the number of rows processed in this chunk.
p.advance(task, len(chunk_df))
# Final status message: print the number of points now in the collection.
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"
)