#!/usr/bin/env python3 """ load_qdrant.py — Load embedded marine doc chunks into Qdrant (hybrid). Collection `marine_docs`: - dense (768-dim, Cosine) from gemini-embedding-2-preview - sparse (BM25 via FastEmbed) for keyword search - payload indexes: product_id, doc_type, chunk_type, section_path Storage: local persistent Qdrant at out/qdrant_db by default (no server needed); pass --url http://localhost:6333 to use a server instead. Usage: python load_qdrant.py --recreate python load_qdrant.py --limit 500 """ import argparse import json import time import uuid from pathlib import Path from qdrant_client import QdrantClient, models from fastembed import SparseTextEmbedding ROOT = Path(__file__).resolve().parent OUT = ROOT / "out" COLLECTION = "marine_docs" DENSE_DIM = 768 INPUT = OUT / "chunks_embedded.jsonl" LOCAL_DB = OUT / "qdrant_db" BATCH = 500 _bm25 = SparseTextEmbedding(model_name="Qdrant/bm25") def to_sparse(text: str) -> models.SparseVector: r = list(_bm25.embed([text]))[0] return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist()) def create_collection(client: QdrantClient, recreate: bool) -> None: names = [c.name for c in client.get_collections().collections] if COLLECTION in names: if recreate: client.delete_collection(COLLECTION) else: print(f"'{COLLECTION}' exists: {client.get_collection(COLLECTION).points_count} pts") return client.create_collection( collection_name=COLLECTION, vectors_config={"dense": models.VectorParams(size=DENSE_DIM, distance=models.Distance.COSINE)}, sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)}, ) for field, schema in [ ("product_id", models.PayloadSchemaType.KEYWORD), ("doc_type", models.PayloadSchemaType.KEYWORD), ("chunk_type", models.PayloadSchemaType.KEYWORD), ("section_path", models.PayloadSchemaType.KEYWORD), ]: client.create_payload_index(collection_name=COLLECTION, field_name=field, field_schema=schema) print(f"created '{COLLECTION}' (dense+sparse, 4 payload indexes)") def load(client: QdrantClient, limit=None) -> None: buf, total, skipped, t0 = [], 0, 0, time.time() with open(INPUT, encoding="utf-8") as f: for i, line in enumerate(f): if limit and i >= limit: break c = json.loads(line) emb = c.get("embedding") if not emb: skipped += 1 continue raw = c.get("text_raw", c.get("text_with_prefix", "")) buf.append(models.PointStruct( id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])), vector={"dense": emb, "sparse": to_sparse(raw)}, payload={ "chunk_id": c["chunk_id"], "product_id": c["product_id"], "product_title": c.get("product_title", ""), "doc_id": c["doc_id"], "doc_type": c["doc_type"], "section_path": c.get("section_path", ""), "chunk_type": c.get("chunk_type", "text"), "text_raw": raw[:2500], }, )) if len(buf) >= BATCH: client.upsert(collection_name=COLLECTION, points=buf) total += len(buf) print(f" [{total:,}] {total/(time.time()-t0):.0f} pts/s") buf = [] if buf: client.upsert(collection_name=COLLECTION, points=buf) total += len(buf) print(f"DONE: {total:,} points, skipped {skipped}, total now " f"{client.get_collection(COLLECTION).points_count:,}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--limit", type=int, default=None) ap.add_argument("--recreate", action="store_true") ap.add_argument("--url", type=str, default=None, help="Qdrant server URL; default = local path mode") a = ap.parse_args() client = QdrantClient(url=a.url, check_compatibility=False) if a.url else QdrantClient(path=str(LOCAL_DB)) print(f"Qdrant: {'server '+a.url if a.url else 'local '+str(LOCAL_DB)}") create_collection(client, a.recreate) load(client, a.limit) if __name__ == "__main__": main()