{ "cells": [ { "cell_type": "markdown", "id": "6504b161", "metadata": {}, "source": [ "# RAG Meets Graph Analytics: Building Hybrid Retrieval on Iceberg with BenoDB\n", "\n", "*By Rick Albright \u00b7 Article 1 of the BenoDB Architecture Series \u00b7 [Documentation](https://www.benolabsai.com/docs/) \u00b7 [GitHub](https://github.com/benolabsai/benodb)*\n", "\n", "---\n", "\n", "Most Graph RAG architectures today present a familiar operational challenge.\n", "\n", "To build an effective retrieval pipeline, engineering teams are typically told to deploy, maintain, and synchronize three separate database clusters: a dedicated vector database for dense embeddings, an inverted-index search engine for keyword search and acronym matching, and a graph database for multihop relationship traversals. Operating separate lakehouse, vector search, and graph systems introduces substantial infrastructure overhead, requires continuous dual-write synchronization to prevent data drift, adds network latency across multiple hops, and fragments data across proprietary storage engines.\n", "\n", "For many application workloads, operating three independent database clusters introduces unnecessary complexity.\n", "\n", "The retrieval thesis for AI agents is straightforward: **unify vectors, keywords, and graph topology in a single storage layer.** Dense vectors capture conceptual similarity, BM25 provides lexical ranking for exact terms and acronyms that dense models may underweight, and graph topology traces inferred semantic relationships across documents.\n", "\n", "We built [BenoDB](https://www.benolabsai.com/docs/) to eliminate this sprawl. By embedding Apache DataFusion in Rust directly over open Apache Iceberg tables, BenoDB runs vector ANN search (HNSW), full-text retrieval (BM25), and graph traversal (CSR) in a single in process engine\u2014with PostgreSQL-compatible pgvector distance operators (`<=>`), zero server daemons, and open Parquet lakehouse storage.\n", "\n", "In this walkthrough, I take **5,183 research abstracts from the Allen Institute for AI's SciFact benchmark** and build an end-to-end Graph RAG pipeline from scratch: from section-aware chunking and in process vector SQL to hardware-adaptive graph derivation and cited LLM answers.\n", "\n", "> **Developer Preview Scope (>= v0.17.1):** Ready today for evaluation and experimentation: embedded in process execution (Python and Rust), pgvector-compatible distance operators (`<=>`, `<->`, `<#>`) embedded in DataFusion, advisory Puffin index sidecars, TurboQuant\u2122 TQ8 quantization, and GPU-accelerated batch distance kernels (`bdb.cdist`). What is intentionally out of scope for this release: distributed multinode consensus, distributed sharding, and multistatement transactions across tables.\n", ">\n", "> **One Canonical Data Store:** Primary records and embeddings reside in standard Parquet files governed by Iceberg. Secondary indexes accelerate retrieval without requiring separate primary-data stores.\n", ">\n", "> **Interactive Notebook:** [Download .ipynb](https://raw.githubusercontent.com/benolabsai/benodb/main/notebooks/graph_rag_howto.ipynb) \u00b7 [View on GitHub](https://github.com/benolabsai/benodb/blob/main/notebooks/graph_rag_howto.ipynb)\n" ] }, { "cell_type": "markdown", "id": "3c30854b", "metadata": {}, "source": [ "## Step 1: Ingesting 5,183 Paper Abstracts (And Why Naive Chunking Destroys RAG)\n", "\n", "Before touching a single line of database code, let's confront the dirty secret of retrieval-augmented generation: **bad chunking will ruin even the best embedding model**.\n", "\n", "If you blindly slice documents every 500 tokens with a fixed sliding window, you will inevitably split a hypothesis in `BACKGROUND` from its refutation in `RESULTS`. When the LLM cites the hypothesis as the finding, your agent hallucinates.\n", "\n", "To keep this real, we aren't using toy synthetic text. We\u2019re loading 5,183 research abstracts from the Allen Institute for AI's SciFact benchmark. Of these, 977 contain explicit section labels such as BACKGROUND, METHODS, RESULTS, and CONCLUSIONS. The accompanying claims dataset provides expert-annotated evidence citations for retrieval evaluation.\n", "\n", "Let's download the corpus and inspect the structure:\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "1407a4f1", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:15.586552Z", "iopub.status.busy": "2026-11-22T21:21:15.586443Z", "iopub.status.idle": "2026-11-22T21:21:15.625323Z", "shell.execute_reply": "2026-11-22T21:21:15.624871Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded 5,183 documents\n", "Structured (labelled sections): 977\n", "\n", "Example doc_id=4983\n", " title: Microstructural development of human newborn cerebral white matter assessed in v\n", " first sentence: Alterations of the architecture of cerebral white matter in the developing human brain can affect co...\n" ] } ], "source": [ "import json\n", "import os\n", "import tarfile\n", "import tempfile\n", "import urllib.request\n", "from pathlib import Path\n", "\n", "# Portable working directory. Override with BENOLABS_WORKDIR if desired.\n", "# Defaults to ./benolabs_howto; if that location is not writable (e.g. a\n", "# downloaded notebook opened from a read-only folder), fall back to the OS\n", "# temp directory, which exists on Linux, macOS, and Windows.\n", "def _default_workdir() -> Path:\n", " env = os.environ.get(\"BENOLABS_WORKDIR\")\n", " if env:\n", " return Path(env).expanduser()\n", " if (Path.cwd() / \"data\" / \"corpus.jsonl\").exists():\n", " return Path.cwd()\n", " if (Path.cwd() / \"notebooks\" / \"data\" / \"corpus.jsonl\").exists():\n", " return Path.cwd() / \"notebooks\"\n", " candidate = Path.cwd() / \"benolabs_howto\"\n", " try:\n", " candidate.mkdir(parents=True, exist_ok=True)\n", " probe = candidate / \".write-test\"\n", " probe.write_text(\"\", encoding=\"utf-8\")\n", " probe.unlink()\n", " return candidate\n", " except OSError:\n", " return Path(tempfile.gettempdir()) / \"benolabs_howto\"\n", "\n", "\n", "WORK_DIR = _default_workdir()\n", "WORK_DIR.mkdir(parents=True, exist_ok=True)\n", "DATA_DIR = WORK_DIR / \"data\"\n", "CORPUS_PATH = DATA_DIR / \"corpus.jsonl\"\n", "ARCHIVE_PATH = DATA_DIR / \"scifact_data.tar.gz\"\n", "URL = \"https://scifact.s3.us-west-2.amazonaws.com/release/latest/data.tar.gz\"\n", "\n", "# Auto-download and extract SciFact corpus on first run\n", "if not CORPUS_PATH.exists():\n", " DATA_DIR.mkdir(parents=True, exist_ok=True)\n", " if not ARCHIVE_PATH.exists():\n", " print(f\"Downloading SciFact corpus from {URL}...\")\n", " urllib.request.urlretrieve(URL, ARCHIVE_PATH)\n", " print(\"Extracting dataset archive safely...\")\n", " target_dir = DATA_DIR.resolve()\n", " with tarfile.open(ARCHIVE_PATH, \"r:gz\") as tar:\n", " for member in tar.getmembers():\n", " if member.name.startswith(\"data/\"):\n", " rel_name = member.name[len(\"data/\"):]\n", " if not rel_name:\n", " continue\n", " dest_path = (target_dir / rel_name).resolve()\n", " if not dest_path.is_relative_to(target_dir):\n", " raise ValueError(f\"Path traversal detected in archive: {member.name}\")\n", " member.name = rel_name\n", " if hasattr(tarfile, \"data_filter\"):\n", " tar.extract(member, path=DATA_DIR, filter=\"data\")\n", " else:\n", " tar.extract(member, path=DATA_DIR)\n", " print(f\"Corpus ready at {CORPUS_PATH}\")\n", "\n", "docs = []\n", "with CORPUS_PATH.open() as f:\n", " for line in f:\n", " r = json.loads(line)\n", " docs.append({\n", " \"doc_id\": int(r[\"doc_id\"]),\n", " \"title\": r[\"title\"],\n", " \"sentences\": r[\"abstract\"], # keep sentence boundaries\n", " \"structured\": bool(r.get(\"structured\", False)),\n", " })\n", "\n", "title_by_id = {d[\"doc_id\"]: d[\"title\"] for d in docs}\n", "\n", "print(f\"Loaded {len(docs):,} documents\")\n", "print(f\"Structured (labelled sections): {sum(d['structured'] for d in docs):,}\")\n", "d = docs[0]\n", "print(f\"\\nExample doc_id={d['doc_id']}\")\n", "print(f\" title: {d['title'][:80]}\")\n", "print(f\" first sentence: {d['sentences'][0][:100]}...\")" ] }, { "cell_type": "markdown", "id": "535a1d04", "metadata": {}, "source": [ "### Intelligent Chunking: Respecting Section Boundaries\n", "\n", "Of these abstracts, 977 contain explicit uppercase section headers. Conventional RAG pipelines rely on fixed 500-token windows with 50-token overlap. In scientific literature, **blind windowing violates structural boundaries:** a chunk spanning METHODS and RESULTS conflates experimental protocol with observed findings, degrading downstream retrieval precision.\n", "\n", "Here, we partition text **strictly within labelled section boundaries**, accumulating sentences into coherent passages up to approximately 80 words (individual sentences that exceed 80 words are preserved intact). If a section ends, the chunk ends. No bleeding, no blurred context:\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "d76feacf", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:15.626620Z", "iopub.status.busy": "2026-11-22T21:21:15.626506Z", "iopub.status.idle": "2026-11-22T21:21:15.710070Z", "shell.execute_reply": "2026-11-22T21:21:15.709602Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "18,404 chunks from 5,183 docs\n", "sections: ['ABSTRACT', 'BACKGROUND', 'CONCLUSION', 'CONCLUSIONS', 'DESIGN', 'DISCUSSION', 'FINDINGS', 'IMPORTANCE']... (21 total)\n", "section nodes: 8,075\n" ] } ], "source": [ "import re\n", "from collections import defaultdict\n", "\n", "SECTION_RE = re.compile(\n", " r\"^(BACKGROUND|OBJECTIVE|OBJECTIVES|PURPOSE|INTRODUCTION|IMPORTANCE|\"\n", " r\"METHODS?|DESIGN|SETTING|PARTICIPANTS|INTERVENTION|MEASUREMENTS|\"\n", " r\"RESULTS?|FINDINGS|DISCUSSION|CONCLUSIONS?|SIGNIFICANCE)\\b\"\n", ")\n", "\n", "\n", "def labelled(sentences):\n", " \"\"\"Yield (section, sentence). Detects all-caps section headers.\"\"\"\n", " section = \"ABSTRACT\"\n", " for s in sentences:\n", " m = SECTION_RE.match(s)\n", " if m:\n", " section = m.group(1)\n", " s = s[m.end():].strip()\n", " if s:\n", " yield section, s\n", "\n", "\n", "def chunk_doc(doc, max_words=80):\n", " \"\"\"List of (section, text), never crossing a section boundary.\"\"\"\n", " out, buf, n, cur = [], [], 0, None\n", " for section, s in labelled(doc[\"sentences\"]):\n", " if cur is not None and section != cur and buf:\n", " out.append((cur, \" \".join(buf))); buf, n = [], 0\n", " cur = section\n", " w = len(s.split())\n", " if buf and n + w > max_words:\n", " out.append((cur, \" \".join(buf))); buf, n = [], 0\n", " buf.append(s); n += w\n", " if buf:\n", " out.append((cur, \" \".join(buf)))\n", " return out\n", "\n", "\n", "rows = []\n", "for d in docs:\n", " for section, text in chunk_doc(d):\n", " rows.append({\n", " \"doc_id\": d[\"doc_id\"],\n", " \"section\": section,\n", " \"section_id\": f\"{d['doc_id']}:{section}\",\n", " \"text\": text,\n", " })\n", "\n", "# The graph engine uses UInt64 node ids, so assign each section a dense node index.\n", "section_ids = sorted({r[\"section_id\"] for r in rows})\n", "node_of = {sid: i for i, sid in enumerate(section_ids)}\n", "label_of = {i: sid for sid, i in node_of.items()}\n", "for r in rows:\n", " r[\"section_node\"] = node_of[r[\"section_id\"]]\n", "\n", "counter = defaultdict(int)\n", "for r in rows:\n", " r[\"chunk_idx\"] = counter[r[\"doc_id\"]]\n", " counter[r[\"doc_id\"]] += 1\n", "\n", "print(f\"{len(rows):,} chunks from {len(docs):,} docs\")\n", "print(f\"sections: {sorted({r['section'] for r in rows})[:8]}... ({len(set(r['section'] for r in rows))} total)\")\n", "print(f\"section nodes: {len(section_ids):,}\")" ] }, { "cell_type": "markdown", "id": "5c6e7808", "metadata": {}, "source": [ "### Generating Dense Embeddings\n", "\n", "From 5,183 research abstracts, we now have **18,404 clean, self-contained chunks** across 8,075 section nodes. Every passage knows its parent document, its section type, and its sequence position.\n", "\n", "Now we encode each passage into a 1024-dimensional dense vector using `BAAI/bge-large-en-v1.5`. We L2-normalize the vectors upfront so that computing cosine similarity reduces to a fast dot product:\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "6ba64f3a", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:15.711343Z", "iopub.status.busy": "2026-11-22T21:21:15.711225Z", "iopub.status.idle": "2026-11-22T21:21:15.836308Z", "shell.execute_reply": "2026-11-22T21:21:15.835795Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded validated precomputed embeddings from data/vectors_bge_large.npy (shape=(18404, 1024), model=BAAI/bge-large-en-v1.5, fingerprint=5061368688498a38)\n", "Embeddings ready: shape=(18404, 1024) dim=1024\n" ] } ], "source": [ "import os, json, hashlib, warnings\n", "from pathlib import Path\n", "import numpy as np\n", "\n", "warnings.filterwarnings(\"ignore\")\n", "\n", "MODEL_NAME = \"BAAI/bge-large-en-v1.5\"\n", "DIM = 1024\n", "QUERY_PREFIX = \"Represent this sentence for searching relevant passages: \"\n", "\n", "model = None\n", "DEVICE = \"cpu\"\n", "\n", "\n", "def get_embedding_model():\n", " \"\"\"Lazily load SentenceTransformer on demand with device fallback.\"\"\"\n", " global model, DEVICE\n", " if model is None:\n", " import torch\n", " from sentence_transformers import SentenceTransformer\n", "\n", " device_env = os.environ.get(\"BENOLABS_EMBED_DEVICE\")\n", " if device_env:\n", " DEVICE = device_env\n", " elif torch.cuda.is_available():\n", " try:\n", " torch.cuda.empty_cache()\n", " _probe = torch.zeros(1, device=\"cuda:0\")\n", " DEVICE = \"cuda:0\"\n", " except Exception:\n", " DEVICE = \"cpu\"\n", " elif torch.backends.mps.is_available():\n", " DEVICE = \"mps\"\n", " else:\n", " DEVICE = \"cpu\"\n", "\n", " try:\n", " model = SentenceTransformer(MODEL_NAME, device=DEVICE, local_files_only=True)\n", " except Exception:\n", " try:\n", " model = SentenceTransformer(MODEL_NAME, device=DEVICE)\n", " except Exception as e:\n", " print(f\"Warning: Failed loading {MODEL_NAME} on {DEVICE} ({e}). Falling back to CPU.\")\n", " DEVICE = \"cpu\"\n", " model = SentenceTransformer(MODEL_NAME, device=DEVICE)\n", " return model\n", "\n", "\n", "def embed_docs(texts):\n", " m = get_embedding_model()\n", " return m.encode(texts, normalize_embeddings=True, show_progress_bar=True, batch_size=256)\n", "\n", "\n", "def embed_query(text):\n", " m = get_embedding_model()\n", " return m.encode([QUERY_PREFIX + text],\n", " normalize_embeddings=True, show_progress_bar=False)[0]\n", "\n", "\n", "# Validate precomputed embedding cache before initializing embedding model\n", "VEC_CACHE = DATA_DIR / \"vectors_bge_large.npy\"\n", "META_CACHE = DATA_DIR / \"vectors_bge_large.meta.json\"\n", "\n", "# Compute deterministic provenance fingerprint over model, dimension, and corpus chunk text\n", "corpus_hasher = hashlib.sha256()\n", "corpus_hasher.update(MODEL_NAME.encode(\"utf-8\"))\n", "corpus_hasher.update(str(DIM).encode(\"utf-8\"))\n", "for r in rows:\n", " corpus_hasher.update(str(r[\"doc_id\"]).encode(\"utf-8\"))\n", " corpus_hasher.update(str(r[\"section\"]).encode(\"utf-8\"))\n", " corpus_hasher.update(r[\"text\"].encode(\"utf-8\"))\n", "corpus_fingerprint = corpus_hasher.hexdigest()[:16]\n", "\n", "cache_valid = False\n", "if VEC_CACHE.exists():\n", " try:\n", " # Inspect array header via memory-map without loading unneeded bytes\n", " mmap_vectors = np.load(VEC_CACHE, mmap_mode=\"r\")\n", " if mmap_vectors.shape != (len(rows), DIM):\n", " print(f\"Cache shape mismatch: {mmap_vectors.shape} vs expected ({len(rows)}, {DIM})\")\n", " elif not META_CACHE.exists():\n", " print(\"Cache unverified: missing metadata provenance file. Re-embedding corpus...\")\n", " else:\n", " with open(META_CACHE, \"r\") as f:\n", " meta = json.load(f)\n", " if meta.get(\"model\") != MODEL_NAME or meta.get(\"dim\") != DIM or meta.get(\"fingerprint\") != corpus_fingerprint:\n", " print(f\"Cache provenance mismatch: expected model={MODEL_NAME}, dim={DIM}, fp={corpus_fingerprint}; found {meta}\")\n", " else:\n", " cache_valid = True\n", " vectors = np.array(mmap_vectors)\n", " except Exception as e:\n", " print(f\"Cache validation error: {e}\")\n", "\n", "if cache_valid:\n", " rel_cache = VEC_CACHE.relative_to(WORK_DIR) if VEC_CACHE.is_relative_to(WORK_DIR) else VEC_CACHE.name\n", " print(f\"Loaded validated precomputed embeddings from {rel_cache} (shape={vectors.shape}, model={MODEL_NAME}, fingerprint={corpus_fingerprint})\")\n", "else:\n", " print(f\"Cache miss: Initializing {MODEL_NAME} to generate embeddings for {len(rows):,} chunks...\")\n", " vectors = embed_docs([r[\"text\"] for r in rows])\n", " VEC_CACHE.parent.mkdir(parents=True, exist_ok=True)\n", " np.save(VEC_CACHE, vectors)\n", " with open(META_CACHE, \"w\") as f:\n", " json.dump({\"model\": MODEL_NAME, \"dim\": DIM, \"rows\": len(rows), \"fingerprint\": corpus_fingerprint}, f, indent=2)\n", " print(f\"Saved embedding cache and provenance metadata to {VEC_CACHE.name}\")\n", "\n", "print(f\"Embeddings ready: shape={vectors.shape} dim={DIM}\")\n" ] }, { "cell_type": "markdown", "id": "0a511a3f", "metadata": {}, "source": [ "## Step 2: Creating the Lakehouse Table (Parquet + Advisory Sidecars)\n", "\n", "At this point, typical RAG architectures introduce unnecessary distributed overhead.\n", "\n", "Conventionally, you would push vectors to Pinecone, serialize text into Elasticsearch, reconcile disparate identifiers across both engines, and operate a CDC pipeline to mitigate synchronization lag.\n", "\n", "In BenoDB, we do something radically simpler: **we write one table directly to open Apache Iceberg storage**.\n", "\n", "We define a standard PyArrow schema, declare our **HNSW vector index** on `embedding`, declare our **BM25 index** on `text`, and commit the data in a single batch:\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "2c9c1e88", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:15.837558Z", "iopub.status.busy": "2026-11-22T21:21:15.837392Z", "iopub.status.idle": "2026-11-22T21:21:18.950427Z", "shell.execute_reply": "2026-11-22T21:21:18.949947Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "error: XDG_RUNTIME_DIR is invalid or not set in the environment.\n", "error: XDG_RUNTIME_DIR is invalid or not set in the environment.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "error: XDG_RUNTIME_DIR is invalid or not set in the environment.\n", "error: XDG_RUNTIME_DIR is invalid or not set in the environment.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Committed 18,404 rows to file:///home/ralbright/projects/benolabs/notebooks/scifact\n", "Indexes ready: hnsw(embedding) + bm25(text)\n" ] } ], "source": [ "import shutil\n", "import pyarrow as pa\n", "import benodb as bdb\n", "\n", "TABLE_DIR = WORK_DIR / \"scifact\"\n", "TABLE_URI = TABLE_DIR.resolve().as_uri()\n", "shutil.rmtree(TABLE_DIR, ignore_errors=True)\n", "\n", "schema = pa.schema([\n", " (\"doc_id\", pa.int64()),\n", " (\"section\", pa.string()),\n", " (\"section_id\", pa.string()),\n", " (\"section_node\", pa.uint64()),\n", " (\"chunk_idx\", pa.int32()),\n", " (\"text\", pa.large_string()),\n", " (\"embedding\", pa.list_(pa.float32(), DIM)),\n", "])\n", "\n", "doc_chunks = bdb.Table.create(TABLE_URI, schema)\n", "\n", "# Configure vector (HNSW) and full-text (BM25) indexes on the table\n", "doc_chunks.add_index(\"embedding\", \"hnsw\")\n", "doc_chunks.add_index(\"text\", \"bm25\")\n", "\n", "# Declare the embedding contract in Iceberg table properties\n", "doc_chunks.set_properties({\n", " \"benostream.embedding.model\": MODEL_NAME,\n", " \"benostream.embedding.dim\": str(DIM),\n", "})\n", "\n", "doc_chunks.write_arrow(pa.table({\n", " \"doc_id\": pa.array([r[\"doc_id\"] for r in rows], pa.int64()),\n", " \"section\": pa.array([r[\"section\"] for r in rows], pa.string()),\n", " \"section_id\": pa.array([r[\"section_id\"] for r in rows], pa.string()),\n", " \"section_node\": pa.array([r[\"section_node\"] for r in rows], pa.uint64()),\n", " \"chunk_idx\": pa.array([r[\"chunk_idx\"] for r in rows], pa.int32()),\n", " \"text\": pa.array([r[\"text\"] for r in rows], pa.large_string()),\n", " \"embedding\": pa.FixedSizeListArray.from_arrays(\n", " pa.array(vectors.reshape(-1), pa.float32()), DIM),\n", "}))\n", "doc_chunks.commit()\n", "doc_chunks.wait_for_background_tasks()\n", "\n", "print(f\"Committed {doc_chunks.row_count:,} rows to {TABLE_URI}\")\n", "print(\"Indexes ready: hnsw(embedding) + bm25(text)\")" ] }, { "cell_type": "markdown", "id": "373a1a69", "metadata": {}, "source": [ "### Under the Hood: Why Lakehouse Storage & Sidecars Matter\n", "\n", "In the ingestion above, BenoDB runs entirely in process, with no external database server running in the background, no Postgres daemon, and no JVM runtime.\n", "\n", "Under the hood, BenoDB wrote standard Apache Parquet data files tracked by an open Apache Iceberg manifest. Two architectural mechanisms make this layout both performant and operationally manageable:\n", "\n", "1. **No Separate Canonical Data Store & Open Standards:** Primary data (text, identifiers, metadata, and Float32 embeddings) resides in standard Parquet files. Because Iceberg is an open table format, data is never locked in a proprietary database silo; the exact same tables remain directly queryable by DuckDB, Trino, or Apache Spark.\n", "2. **Advisory Puffin Sidecars vs. Edge Tables:**\n", " - **HNSW and BM25 Sidecars:** Secondary retrieval indexes (HNSW graphs for vectors and BM25 inverted lists for text) are stored alongside Parquet files as advisory sidecars in standard Apache Iceberg Puffin format bound to table snapshots. If an index is rebuilt or dropped, canonical table rows remain untouched.\n", " - **Graph Topology Storage:** In this walkthrough, relationship edges are persisted as an independent Apache Iceberg edge table (`scifact_links`) in standard Parquet format. When graph operations run, the embedded engine loads the edge table into an in-memory Compressed Sparse Row (CSR) matrix for vectorized traversal and community detection. \n", "\n", "**Production Scale & Quantization:** In this walkthrough, we built an uncompressed Float32 HNSW index (`hnsw`). For multi-million-row datasets where memory is constrained, BenoDB supports pluggable 8-bit quantization (`hnsw_tq8` with randomized Walsh-Hadamard rotation on power-of-two dimensions, achieving >98% Recall@10 on the NeurIPS BigANN benchmark, and `sq8` for uniform scalar quantization), combined with second-pass Float32 reranking read directly from 32 KB Parquet data pages.\n", "\n", "> \ud83d\udcd6 **Dive Deeper:** For complete storage layout specifications, Iceberg table properties, and memory budgeting rules, see the [Lakehouse Architecture Guide](https://www.benolabsai.com/docs/guides/architecture.html) and [Resource Limits & Memory Discipline](https://www.benolabsai.com/docs/guides/resource_limits.html)." ] }, { "cell_type": "markdown", "id": "d0aba8e1", "metadata": {}, "source": [ "## Step 3: In Process SQL with Native pgvector Syntax\n", "\n", "Now that our data and indexes are committed to the lakehouse, how do we query them?\n", "\n", "Instead of inventing a bespoke query language or requiring developers to spin up a Postgres server just to get vector operators, BenoDB embeds Apache DataFusion in Rust. This exposes embedded DataFusion SQL with **pgvector-compatible distance operators** (`<=>` cosine distance, `<->` Euclidean L2 distance, `<#>` negative inner product) directly over Parquet tables in process:" ] }, { "cell_type": "code", "execution_count": 5, "id": "12b73854", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:18.951855Z", "iopub.status.busy": "2026-11-22T21:21:18.951652Z", "iopub.status.idle": "2026-11-22T21:21:18.967797Z", "shell.execute_reply": "2026-11-22T21:21:18.967127Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Registered 'doc_chunks' with 18,404 rows in Apache DataFusion session.\n" ] } ], "source": [ "session = bdb.Session()\n", "session.register(\"doc_chunks\", doc_chunks)\n", "\n", "# Inspect table health via in process DataFusion SQL\n", "df_cnt = session.sql(\"SELECT count(*) AS chunks FROM doc_chunks\").to_pandas()\n", "print(f\"Registered 'doc_chunks' with {df_cnt.iloc[0]['chunks']:,} rows in Apache DataFusion session.\")\n" ] }, { "cell_type": "markdown", "id": "14ac8758", "metadata": {}, "source": [ "### Querying Vectors: Table API vs. In Process pgvector SQL\n", "\n", "To establish our baseline, let's query the table for a test claim:\n", "$$\\text{\"smoking increases the risk of lung cancer\"}$$\n", "\n", "We can execute pure vector similarity search in two ways: via the high-level Python Table API (`doc_chunks.vector_search`), or via **pgvector-compatible distance operators in embedded SQL** using the `<=>` cosine distance operator inside Apache DataFusion.\n", "\n", "Supported pgvector operators include:\n", "- `<=>` : Cosine distance ($1 - \\text{cosine similarity}$)\n", "- `<->` : Euclidean L2 distance\n", "- `<#>` : Negative inner product\n", "\n", "Let's run both and inspect what pure vector search returns:\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "99094873", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:18.968902Z", "iopub.status.busy": "2026-11-22T21:21:18.968785Z", "iopub.status.idle": "2026-11-22T21:21:24.623336Z", "shell.execute_reply": "2026-11-22T21:21:24.622586Z" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "f792556cb5314eaab6e2c89c7c9b4afc", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Loading weights: 0%| | 0/391 [00:00 Operator) ---\n", " [7639744] (RESULTS #4, dist: 0.1693) Influence of smoking cessation after diagnosis of early stage lun\n", " [26067999] (ABSTRACT #17, dist: 0.1890) Screening for Lung Cancer: U.S. Preventive Services Task Force Re\n", " [26067999] (ABSTRACT #4, dist: 0.2050) Screening for Lung Cancer: U.S. Preventive Services Task Force Re\n" ] } ], "source": [ "query = \"smoking increases the risk of lung cancer\"\n", "qvec = embed_query(query).tolist()\n", "\n", "# A. Vector ANN Search via Python Table API\n", "v_hits = doc_chunks.vector_search(\"embedding\", qvec, k=3, metric=\"cosine\")\n", "print(f\"Query: {query!r}\\n\")\n", "print(\"--- Standalone Vector Search Hits (HNSW Index) ---\")\n", "for _, r in v_hits.iterrows():\n", " doc = int(r[\"doc_id\"])\n", " print(f\" [{doc}] ({r['section']} #{r['chunk_idx']}, dist: {r['distance']:.4f}) {title_by_id.get(doc, '')[:65]}\")\n", "\n", "# B. pgvector-Compatible Distance Query in DataFusion SQL (<=> Operator)\n", "sql_hits = session.sql(f\"\"\"\n", " SELECT doc_id, section, chunk_idx, text,\n", " embedding <=> {qvec} AS cosine_dist\n", " FROM doc_chunks\n", " ORDER BY cosine_dist ASC\n", " LIMIT 3\n", "\"\"\").to_pandas()\n", "print(\"\\n--- In Process pgvector SQL Query in DataFusion (<=> Operator) ---\")\n", "for _, r in sql_hits.iterrows():\n", " doc = int(r[\"doc_id\"])\n", " print(f\" [{doc}] ({r['section']} #{r['chunk_idx']}, dist: {r['cosine_dist']:.4f}) {title_by_id.get(doc, '')[:65]}\")\n" ] }, { "cell_type": "markdown", "id": "0b1585e3", "metadata": {}, "source": [ "### Distance Representations: Table API vs. Embedded SQL\n", "\n", "If you look closely at the outputs above, both methods retrieved the **exact same three documents in the exact same rank order**, but their distance metrics report different numerical values:\n", "\n", "1. **Table API (`doc_chunks.vector_search(..., metric=\"cosine\")`):** When the HNSW index was created in Step 2 via `doc_chunks.add_index(\"embedding\", \"hnsw\")`, the engine constructed an HNSW graph using its default build metric (`IndexAlgorithm::Hnsw { metric: \"l2\", ... }`). At query time, `vector_search` resolves through the accelerated index path (`search_hnsw_ivf`), which traverses the graph using the index internal distance metric ($L_2$). Because all embeddings were normalized ($\\|u\\|_2 = 1$) during Step 1, Euclidean distance is monotonically equivalent to cosine distance ($d_{L_2} = \\sqrt{2 \\cdot d_{\\text{cosine}}}$), preserving identical nearest neighbor ordering. The index search returns its internal graph distance representation: chordal Euclidean $L_2$ distance ($0.5819$).\n", "2. **In Process SQL (`<=>` operator):** Computes exact pgvector-compatible **cosine distance** inside DataFusion:\n", " $$d_{\\text{cosine}} = 1 - \\cos \\theta = 1 - \\frac{\\langle u, v \\rangle}{\\|u\\|_2 \\|v\\|_2} = \\mathbf{0.1693}$$\n", "\n", "The two values are related by the standard unit-sphere conversion:\n", "$$d_{L_2} = \\sqrt{2(1 - \\cos \\theta)} = \\sqrt{2 \\times 0.1693} = \\mathbf{0.5819}$$\n", "\n", "Both representations produce identical topological candidate rankings. The Table API executes accelerated HNSW graph traversal over advisory Puffin sidecars, while SQL provides PostgreSQL-compatible distance operators (`<=>`, `<->`, `<#>`) for analytical joins, filtering, and ad hoc expressions directly within DataFusion queries.\n", "\n", "> \ud83d\udcd6 **Dive Deeper:** For the complete catalog of supported pgvector operators, analytical joins on embeddings, and DataFusion execution details, explore the [pgvector SQL Guide](https://www.benolabsai.com/docs/guides/pgvector_sql_guide.html)." ] }, { "cell_type": "markdown", "id": "32b6c298", "metadata": {}, "source": [ "## Step 4: Hybrid Search in Action: Fusing Vectors and BM25\n", "\n", "Pure vector search found semantically relevant passages, but anyone who has shipped RAG to production knows its Achilles' heel: **vector models frequently flub exact acronyms, chemical formulas, and product codes**. Conversely, BM25 provides lexical ranking for exact terms, acronyms, and product codes, providing a complementary signal to dense semantic vectors.\n", "\n", "Operating separate vector and keyword search clusters introduces unnecessary coordination:\n", "1. Sending an ANN request to Pinecone or Qdrant,\n", "2. Sending a text query to Elasticsearch or OpenSearch,\n", "3. Waiting for both remote responses over the network, and\n", "4. Computing rank fusion in your application code.\n", "\n", "`doc_chunks.hybrid_search()` eliminates that multi-service coordination. It evaluates dense vector ANN and BM25 index paths concurrently over advisory Puffin sidecars and fuses candidate ranks in-engine using **Reciprocal Rank Fusion (RRF)**:\n", "\n", "$$\\text{RRF}(d) = \\sum_{m \\in \\{\\text{dense}, \\text{bm25}\\}} \\frac{1}{k + \\text{rank}_m(d)}$$\n", "\n", "Where $k=60$ is the standard smoothing constant, and $\\text{rank}_m(d) \\in \\{1, 2, \\dots\\}$ is the 1-based rank of item $d$ within modality $m$.\n", "\n", "With two retrieval modalities, the theoretical maximum possible score under this formula occurs when a candidate places rank #1 in both the dense vector and BM25 candidate lists:\n", "\n", "$$\\text{RRF}_{\\max} = \\frac{1}{60 + 1} + \\frac{1}{60 + 1} = \\frac{2}{61} \\approx \\mathbf{0.03279}$$\n", "\n", "Whether your data lives on local disk or in cloud object storage (such as an S3 or MinIO bucket accessed from a developer laptop), the engine evaluates vector distances and BM25 postings directly against the Iceberg index sidecars, fusing scores in-engine before returning top candidates to your Python runtime.\n", "\n", "Let's run the exact same query through hybrid search and watch what changes:" ] }, { "cell_type": "code", "execution_count": 7, "id": "018fafdc", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:24.624836Z", "iopub.status.busy": "2026-11-22T21:21:24.624538Z", "iopub.status.idle": "2026-11-22T21:21:24.663967Z", "shell.execute_reply": "2026-11-22T21:21:24.663404Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Query: 'smoking increases the risk of lung cancer'\n", "\n", "--- Top Hybrid Search Hits (Dense Vector + BM25 RRF) ---\n", " doc_id section chunk_idx rrf_score\n", "26067999 ABSTRACT 4 0.032266\n", "26067999 ABSTRACT 17 0.032258\n", " 7639744 CONCLUSIONS 7 0.030118\n", "12145359 RESULTS 2 0.030090\n", "16422880 OBJECTIVE 1 0.029851\n", "\n", "Top Hit Titles:\n", " [26067999] Screening for Lung Cancer: U.S. Preventive Services Task Force Recommendation \n", " [26067999] Screening for Lung Cancer: U.S. Preventive Services Task Force Recommendation \n", " [7639744] Influence of smoking cessation after diagnosis of early stage lung cancer on p\n" ] } ], "source": [ "TOP_K = 5\n", "\n", "hits = doc_chunks.hybrid_search(\n", " text_column=\"text\",\n", " query_text=query,\n", " vector_column=\"embedding\",\n", " query_vector=qvec,\n", " k=TOP_K,\n", ").sort_values(\"rrf_score\", ascending=False).reset_index(drop=True)\n", "print(f\"Query: {query!r}\\n\")\n", "print(\"--- Top Hybrid Search Hits (Dense Vector + BM25 RRF) ---\")\n", "print(hits[[\"doc_id\", \"section\", \"chunk_idx\", \"rrf_score\"]].to_string(index=False))\n", "print(\"\\nTop Hit Titles:\")\n", "for _, r in hits.head(3).iterrows():\n", " doc = int(r[\"doc_id\"])\n", " print(f\" [{doc}] {title_by_id.get(doc, '')[:78]}\")\n" ] }, { "cell_type": "markdown", "id": "33ad559d", "metadata": {}, "source": [ "Notice what happened when BM25 keyword matching and dense vector scores were fused:\n", "\n", "1. **Direct Evidence Promoted to #1:** Under hybrid search, BM25 matched the exact query tokens (*\"smoking\"*, *\"risk\"*, *\"lung cancer\"*), propelling document `26067999 Chunk #4` directly to rank #1 with an in-engine `rrf_score` of `0.032266` ($k=60$). In contrast to standalone vector retrieval (which ranked document `7639744` first based on smoking *cessation after diagnosis*), fusing lexical and vector scoring elevated the passage with the definitive evidentiary sentence: *\"The most important risk factor for lung cancer is smoking, which results in approximately 85% of all U.S. lung cancer cases.\"*\n", "2. **Direct Epidemiological Studies Rescued:** Hybrid search elevated document `16422880` (*\"Effect of smoking reduction on lung cancer risk\"*) into the top candidates (`rrf_score: 0.029851`), capturing direct study data on lung cancer incidence that dense vector similarity had ranked lower down the candidate list.\n", "\n", "### Scoped Search: SQL Predicate Pushdown\n", "\n", "When an agent needs evidence for a claim, searching `METHODS` or `BACKGROUND` is often unhelpful. You want results strictly from `RESULTS` or `CONCLUSIONS`. BenoDB pushes SQL `filter` expressions directly into the storage engine before scoring, pruning index evaluation:\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "5a55375c", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:24.665326Z", "iopub.status.busy": "2026-11-22T21:21:24.665202Z", "iopub.status.idle": "2026-11-22T21:21:24.775444Z", "shell.execute_reply": "2026-11-22T21:21:24.774881Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Filtered strictly to Results & Conclusions:\n", "\n", " doc_id section chunk_idx rrf_score\n", "12145359 RESULTS 2 0.032002\n", " 7639744 CONCLUSIONS 7 0.032002\n", " 7639744 RESULTS 4 0.031545\n", " 7639744 RESULTS 5 0.031010\n", " 4828631 FINDINGS 4 0.030118\n" ] } ], "source": [ "scoped = doc_chunks.hybrid_search(\n", " text_column=\"text\",\n", " query_text=query,\n", " vector_column=\"embedding\",\n", " query_vector=qvec,\n", " k=TOP_K,\n", " filter=\"section IN ('RESULTS', 'RESULT', 'FINDINGS', 'CONCLUSIONS', 'CONCLUSION')\",\n", ").sort_values(\"rrf_score\", ascending=False).reset_index(drop=True)\n", "print(\"Filtered strictly to Results & Conclusions:\\n\")\n", "print(scoped[[\"doc_id\", \"section\", \"chunk_idx\", \"rrf_score\"]].to_string(index=False))\n" ] }, { "cell_type": "markdown", "id": "4273abf9", "metadata": {}, "source": [ "### Context Window Expansion: Adjacent Chunks in SQL\n", "\n", "When an agent retrieves an isolated snippet, it often needs the surrounding narrative to synthesize an accurate answer. Because our table preserves `chunk_idx` sequentially across the abstract, pulling adjacent chunks ($c-1, c, c+1$) in a single in process SQL query provides surrounding context.\n", "\n", "Because `chunk_idx` is assigned sequentially across the entire document rather than independently within each section, an unconstrained query could inadvertently cross from `RESULTS` into `METHODS` or `BACKGROUND`. Scoping the query with `AND section = '{top_section}'` guarantees that adjacent chunk retrieval strictly respects section boundaries:" ] }, { "cell_type": "code", "execution_count": 9, "id": "30296025", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:24.776637Z", "iopub.status.busy": "2026-11-22T21:21:24.776514Z", "iopub.status.idle": "2026-11-22T21:21:24.793496Z", "shell.execute_reply": "2026-11-22T21:21:24.792881Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Context Window around doc_id=26067999 [ABSTRACT #4]:\n", "\n", "[ABSTRACT #3] Appendix Table 1 describes the USPSTF grades, and Appendix Table 2 describes the USPSTF classification of levels of cert...\n", "[ABSTRACT #4] The most important risk factor for lung cancer is smoking, which results in approximately 85% of all U.S. lung cancer ca...\n", "[ABSTRACT #5] Lung cancer has a poor prognosis, and nearly 90% of persons with lung cancer die of the disease. However, early-stage no...\n" ] } ], "source": [ "top = hits.iloc[0]\n", "top_doc, top_ci, top_section = int(top[\"doc_id\"]), int(top[\"chunk_idx\"]), str(top[\"section\"])\n", "\n", "win = session.sql(f'''\n", " SELECT section, chunk_idx, text\n", " FROM doc_chunks\n", " WHERE doc_id = {top_doc}\n", " AND section = '{top_section}'\n", " AND chunk_idx BETWEEN {top_ci - 1} AND {top_ci + 1}\n", " ORDER BY chunk_idx\n", "''').to_pandas()\n", "\n", "print(f\"Context Window around doc_id={top_doc} [{top_section} #{top_ci}]:\\n\")\n", "for _, r in win.iterrows():\n", " print(f\"[{r['section']} #{r['chunk_idx']}] {r['text'][:120]}...\")" ] }, { "cell_type": "markdown", "id": "f9a8e8f1", "metadata": {}, "source": [ "> \ud83d\udcd6 **Dive Deeper:** For the complete Python API reference covering hybrid scoring parameters, predicate pushdown filters, and candidate re-ranking, see the [Python Vector API Documentation](https://www.benolabsai.com/docs/guides/python_vector_api.html).\n" ] }, { "cell_type": "markdown", "id": "e7efd4f4", "metadata": {}, "source": [ "## Step 5: 50-Claim SciFact Retrieval Experiment (Illustrative Evaluation)\n", "\n", "A single example demonstrates the mechanics, but evaluating across a multi-query sample provides a more useful check of retrieval behavior against ground truth.\n", "\n", "To evaluate retrieval behavior systematically, we examine an illustrative **50-claim evaluation subset** from the Allen Institute for AI's [SciFact](https://github.com/allenai/scifact) benchmark (`claims_dev.jsonl`). Each claim has expert-annotated ground-truth evidence citations (`cited_doc_ids`). Note that expert evidence annotations belong to the claims evaluation set; they are not annotations attached to every corpus abstract. This evaluation provides a structured diagnostic check of relative strategy behavior on a sample workload, rather than a claim of definitive benchmark superiority.\n", "\n", "We evaluate the first 50 eligible claims with ground-truth evidence citations (`eval_subset = eval_claims[:50]`) across three retrieval strategies targeting $K=10$ unique documents:\n", "1. **BM25 Only:** Lexical ranking over the inverted index.\n", "2. **Vector Only:** Cosine similarity over normalized `bge-large-en-v1.5` dense embeddings.\n", "3. **Hybrid Search:** Reciprocal Rank Fusion ($k=60$) combining vector distance and BM25 postings.\n", "\n", "We compute macro-averaged mean per-query metrics: **document-level Recall@10** (fraction of ground-truth cited documents retrieved) and **document-level nDCG@10** (Normalized Discounted Cumulative Gain, weighting document hits by rank position). This evaluates evidence-source recovery (retrieving the cited papers) rather than passage-level span extraction or claim entailment.\n", "\n", "> **Methodological Note on Chunk Deduplication & Candidate Depth:**\n", "> Because the underlying index evaluates passage chunks while the SciFact benchmark evaluates document citations (`doc_id`), the evaluation retrieves a candidate pool of 50 chunks (`CANDIDATE_POOL = 50`) and deduplicates returned chunks by `doc_id` to assemble the top-10 unique documents per query. If a document contributes multiple chunks, deduplication ensures only the highest-ranked chunk determines the document's rank position.\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "a704f19e", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:24.795073Z", "iopub.status.busy": "2026-11-22T21:21:24.794924Z", "iopub.status.idle": "2026-11-22T21:21:26.777683Z", "shell.execute_reply": "2026-11-22T21:21:26.777238Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Retrieval Strategy Recall@10 nDCG@10 N_valid Errors \n", "------------------------------------------------------------------\n", "BM25 Only 0.8400 0.6967 50 0 \n", "Vector Only (BGE) 0.8860 0.8350 50 0 \n", "Hybrid (RRF) 0.9010 0.8096 50 0 \n" ] } ], "source": [ "CLAIMS_PATH = DATA_DIR / \"claims_dev.jsonl\"\n", "eval_claims = []\n", "with CLAIMS_PATH.open() as f:\n", " for line in f:\n", " c = json.loads(line)\n", " if c.get(\"cited_doc_ids\"):\n", " eval_claims.append(c)\n", "\n", "# First 50 eligible claims with ground-truth evidence citations\n", "eval_subset = eval_claims[:50]\n", "\n", "eval_results = {\n", " \"BM25 Only\": {\"recall\": [], \"ndcg\": []},\n", " \"Vector Only (BGE)\": {\"recall\": [], \"ndcg\": []},\n", " \"Hybrid (RRF)\": {\"recall\": [], \"ndcg\": []},\n", "}\n", "eval_errors = {\n", " \"BM25 Only\": [],\n", " \"Vector Only (BGE)\": [],\n", " \"Hybrid (RRF)\": [],\n", "}\n", "\n", "K = 10\n", "CANDIDATE_POOL = 50 # Oversample chunks before deduplicating to unique documents\n", "\n", "for item in eval_subset:\n", " q_text = item[\"claim\"]\n", " q_vec = embed_query(q_text)\n", " ground_truth = set(int(x) for x in item[\"cited_doc_ids\"])\n", "\n", " # 1. BM25 Only: Passing a string query to a BM25-indexed column routes directly to Okapi BM25\n", " try:\n", " bm25_res = doc_chunks.vector_search(\"text\", q_text, k=CANDIDATE_POOL)\n", " bm25_docs = []\n", " for d in bm25_res[\"doc_id\"]:\n", " if d not in bm25_docs:\n", " bm25_docs.append(d)\n", " if len(bm25_docs) == K: break\n", " hits_cnt = len(ground_truth.intersection(bm25_docs))\n", " eval_results[\"BM25 Only\"][\"recall\"].append(hits_cnt / len(ground_truth))\n", " dcg = sum(1.0 / np.log2(rank + 2) for rank, d in enumerate(bm25_docs) if d in ground_truth)\n", " idcg = sum(1.0 / np.log2(rank + 2) for rank in range(min(len(ground_truth), K)))\n", " eval_results[\"BM25 Only\"][\"ndcg\"].append(dcg / idcg if idcg > 0 else 0.0)\n", " except Exception as e:\n", " eval_errors[\"BM25 Only\"].append(str(e))\n", "\n", " # 2. Vector Only: Pure HNSW index traversal over normalized dense embeddings\n", " try:\n", " vec_res = doc_chunks.vector_search(\"embedding\", q_vec, k=CANDIDATE_POOL, metric=\"cosine\")\n", " vec_docs = []\n", " for d in vec_res[\"doc_id\"]:\n", " if d not in vec_docs:\n", " vec_docs.append(d)\n", " if len(vec_docs) == K: break\n", " hits_cnt = len(ground_truth.intersection(vec_docs))\n", " eval_results[\"Vector Only (BGE)\"][\"recall\"].append(hits_cnt / len(ground_truth))\n", " dcg = sum(1.0 / np.log2(rank + 2) for rank, d in enumerate(vec_docs) if d in ground_truth)\n", " idcg = sum(1.0 / np.log2(rank + 2) for rank in range(min(len(ground_truth), K)))\n", " eval_results[\"Vector Only (BGE)\"][\"ndcg\"].append(dcg / idcg if idcg > 0 else 0.0)\n", " except Exception as e:\n", " eval_errors[\"Vector Only (BGE)\"].append(str(e))\n", "\n", " # 3. Hybrid Search: In-engine Reciprocal Rank Fusion (RRF, k=60)\n", " try:\n", " hyb_res = doc_chunks.hybrid_search(\n", " text_column=\"text\",\n", " query_text=q_text,\n", " vector_column=\"embedding\",\n", " query_vector=q_vec,\n", " k=CANDIDATE_POOL,\n", " ).sort_values(\"rrf_score\", ascending=False).reset_index(drop=True)\n", " hyb_docs = []\n", " for d in hyb_res[\"doc_id\"]:\n", " if d not in hyb_docs:\n", " hyb_docs.append(d)\n", " if len(hyb_docs) == K: break\n", " hits_cnt = len(ground_truth.intersection(hyb_docs))\n", " eval_results[\"Hybrid (RRF)\"][\"recall\"].append(hits_cnt / len(ground_truth))\n", " dcg = sum(1.0 / np.log2(rank + 2) for rank, d in enumerate(hyb_docs) if d in ground_truth)\n", " idcg = sum(1.0 / np.log2(rank + 2) for rank in range(min(len(ground_truth), K)))\n", " eval_results[\"Hybrid (RRF)\"][\"ndcg\"].append(dcg / idcg if idcg > 0 else 0.0)\n", " except Exception as e:\n", " eval_errors[\"Hybrid (RRF)\"].append(str(e))\n", "\n", "print(f\"\\n{'Retrieval Strategy':<22} {'Recall@10':<12} {'nDCG@10':<12} {'N_valid':<10} {'Errors':<8}\")\n", "print(\"-\" * 66)\n", "for name in [\"BM25 Only\", \"Vector Only (BGE)\", \"Hybrid (RRF)\"]:\n", " recalls = eval_results[name][\"recall\"]\n", " ndcgs = eval_results[name][\"ndcg\"]\n", " n_valid = len(recalls)\n", " err_cnt = len(eval_errors[name])\n", " r_score = np.mean(recalls) if n_valid > 0 else 0.0\n", " n_score = np.mean(ndcgs) if n_valid > 0 else 0.0\n", " print(f\"{name:<22} {r_score:<12.4f} {n_score:<12.4f} {n_valid:<10} {err_cnt:<8}\")" ] }, { "cell_type": "markdown", "id": "c1fa577e", "metadata": {}, "source": [ "### Interpreting the Results: What the Numbers Actually Mean\n", "\n", "Look closely at the macro-averaged mean per-query numbers from the 50-claim evaluation above (evaluated against official SciFact ground truth with BAAI/bge-large-en-v1.5 embeddings):\n", "\n", "| Retrieval Strategy | Document Recall@10 | Document nDCG@10 | Valid Denominator ($N$) | Errors | Engineering Takeaway |\n", "|---|---|---|---|---|---|\n", "| **BM25 Only** | 0.8400 | 0.6967 | 50 | 0 | Fast lexical matching; misses conceptual paraphrases |\n", "| **Vector Only (BGE)** | 0.8860 | 0.8350 | 50 | 0 | High ranking quality; susceptible to keyword misses |\n", "| **Hybrid (RRF)** | 0.9010 | 0.8096 | 50 | 0 | Highest aggregate recall; robust dual-signal candidate generation |\n", "\n", "1. **Hybrid Retrieval Recovers Highest Aggregate Recall (0.9010 Recall@10, 0.8096 nDCG@10):** By fusing BM25 lexical postings with dense vector ranking, Hybrid RRF achieved a macro-averaged per-query Recall@10 of 0.9010\u2014outperforming pure dense retrieval (0.8860) and pure BM25 (0.8400). The dual-signal candidate pool allows lexical retrieval to help recover exact terminology and nomenclature (e.g. specific genes, drugs, or numerical thresholds) that dense retrieval underweights.\n", "2. **Dense Vector Ranking Quality (0.8860 Recall@10, 0.8350 nDCG@10):** Dense embeddings achieved the highest ranking quality (0.8350 nDCG@10), placing relevant documents near the top of the result list when semantic context was strong. Research claims often use generalized abstractions or medical synonyms that do not share exact tokens with abstract text, allowing semantic representations to excel.\n", "3. **BM25 Lexical Ranking (0.8400 Recall@10, 0.6967 nDCG@10):** BM25 provides fast lexical term matching, successfully recovering ground-truth documents when claims contain distinctive acronyms or gene symbols, but dropping recall when terminology diverges.\n", "4. **Engineering Takeaway:** Combining both modalities into a single in process engine with Reciprocal Rank Fusion ($k=60$) balances ranking quality and recall without requiring separate search infrastructure or asynchronous replication pipelines.\n" ] }, { "cell_type": "markdown", "id": "2fd99223", "metadata": {}, "source": [ "## Step 6: Adding Graph Topology: Inferred Directed Semantic Similarity Graph (Without Operating Neo4j)\n", "\n", "Hybrid search nails single-passage retrieval. But what happens when an agent needs to explore related research context across multiple documents?\n", "\n", "Traditionally, adding graph capabilities means provisioning a dedicated graph database cluster (such as Neo4j or Amazon Neptune). That introduces a third database bill, another query language to learn, and an asynchronous ETL synchronization pipeline that can drift out of sync.\n", "\n", "In BenoDB, **graph edges are simply another standard Apache Iceberg table** stored right alongside your documents in open Parquet format. When you query the graph, the embedded Rust engine compiles the table into an in-memory **Compressed Sparse Row (CSR)** representation on the fly, running vectorized graph traversals in process.\n", "\n", "### Deriving the Inferred Semantic Similarity Topology\n", "SciFact research abstracts do not include citation graphs or curated entity-relation ontologies. Instead, we derive a **directed $k$-nearest neighbor semantic similarity topology** ($k=5$):\n", "- We pool chunk embeddings by section node.\n", "- We compute batched pairwise cosine distances using BenoDB's batch distance kernel (`bdb.cdist`). BenoDB supports CUDA, Metal, WGPU, and CPU SIMD execution. This notebook run used the CPU backend (`device=cpu`), computing all 65.2 million pairwise cosine distances in process in ~15 seconds. GPU backends are supported and can accelerate this operation; performance depends on the hardware and workload.\n", "- Each section connects to its top-$K$ most similar sections ($K=5$) using `np.argpartition` to select neighbors in $O(S)$ time per row without sorting the full matrix. Because each node independently selects its nearest neighbors, this produces a directed $k$-NN graph ($8,075 \\times 5 = 40,375$ directed edges); an edge from node $A$ to node $B$ does not imply a reciprocal edge from $B$ to $A$.\n", "\n", "> **Memory Complexity of Pairwise Similarity ($O(S^2)$):**\n", "> Computing the full pairwise similarity matrix across $S = 8,075$ section centroids requires allocating an $S \\times S$ Float32 array:\n", "> $$8,075 \\times 8,075 \\times 4\\text{ bytes} \\approx \\mathbf{260.8\\text{ MB}}$$\n", "> Using `np.argpartition` selects the top-5 neighbors in $O(S)$ time per row, avoiding a full $O(S \\log S)$ sort of every row across the dense $8,075 \\times 8,075$ matrix.\n", ">\n", "> **Production Alternative (Not demonstrated in this notebook):** For enterprise-scale graphs where $S > 100,000$ (where an $S \\times S$ dense matrix would exceed 40 GB of RAM), graphs are constructed by streaming batched $k$-NN candidate searches against an HNSW index sidecar rather than allocating a dense pairwise similarity matrix. See the [Graph Construction Benchmark Guide](https://www.benolabsai.com/docs/guides/graph_rag_edge_tables.html) for that workflow.\n", ">\n", "> **Architectural Boundary on Cross-Table Synchronization:** `doc_chunks` and `scifact_links` are independently committed Apache Iceberg tables. Graph topology is derived from the underlying section embeddings and can be reconstructed or updated when document tables change. While BenoDB eliminates the infrastructure and network tax of managing an external graph database daemon (e.g. Neo4j), applications that mutate document embeddings remain responsible for maintaining or rebuilding the corresponding derived edge table.\n", "\n", "This graph represents **semantic graph exploration**: connecting conceptually related experimental findings across papers to enable multihop local context expansion during retrieval." ] }, { "cell_type": "code", "execution_count": 11, "id": "94647b6d", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:26.779179Z", "iopub.status.busy": "2026-11-22T21:21:26.779057Z", "iopub.status.idle": "2026-11-22T21:21:41.671516Z", "shell.execute_reply": "2026-11-22T21:21:41.671056Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8,075 section nodes, 40,375 edges (K=5)\n", "Pairwise similarity computed with bdb.cdist in 14.19s (device=cpu)\n" ] } ], "source": [ "import time\n", "from collections import defaultdict\n", "\n", "by_node = defaultdict(list)\n", "for r, v in zip(rows, vectors):\n", " by_node[r[\"section_node\"]].append(v)\n", "\n", "node_ids = sorted(by_node)\n", "node_vecs = np.stack([np.mean(by_node[n], axis=0) for n in node_ids])\n", "node_vecs /= np.linalg.norm(node_vecs, axis=1, keepdims=True)\n", "\n", "K = 5\n", "# Hardware-accelerated batch distance: CUDA (NVIDIA), MPS (Apple Metal), WGPU (AMD/Intel), or CPU SIMD\n", "cdist_device = bdb.Device(\"auto\").backend\n", "t0 = time.perf_counter()\n", "sims = 1.0 - bdb.cdist(node_vecs, node_vecs, metric=\"cosine\", device=cdist_device)\n", "cdist_duration = time.perf_counter() - t0\n", "np.fill_diagonal(sims, -np.inf)\n", "# np.argpartition selects top-K in O(S) time per row, avoiding a full O(S log S) sort\n", "nbr = np.argpartition(-sims, K, axis=1)[:, :K]\n", "\n", "edge_src, edge_dst, edge_w = [], [], []\n", "for i, nid in enumerate(node_ids):\n", " for j in nbr[i]:\n", " edge_src.append(nid); edge_dst.append(node_ids[j]); edge_w.append(float(sims[i, j]))\n", "\n", "print(f\"{len(node_ids):,} section nodes, {len(edge_src):,} edges (K={K})\")\n", "print(f\"Pairwise similarity computed with bdb.cdist in {cdist_duration:.2f}s (device={cdist_device or 'cpu'})\")\n" ] }, { "cell_type": "markdown", "id": "990cd509", "metadata": {}, "source": [ "### Writing the Relationship Edge Table\n", "\n", "We commit our edges to a second Iceberg table in the catalog: `scifact_links`:\n" ] }, { "cell_type": "code", "execution_count": 12, "id": "79b79e0c", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:41.673058Z", "iopub.status.busy": "2026-11-22T21:21:41.672951Z", "iopub.status.idle": "2026-11-22T21:21:41.700127Z", "shell.execute_reply": "2026-11-22T21:21:41.699463Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Edge table: 40,375 edges, columns=['source', 'target', 'relation', 'weight']\n" ] } ], "source": [ "EDGE_DIR = WORK_DIR / \"scifact_links\"\n", "EDGE_URI = EDGE_DIR.resolve().as_uri()\n", "shutil.rmtree(EDGE_DIR, ignore_errors=True)\n", "\n", "links = bdb.Table.create_edge_table(EDGE_URI)\n", "links.write_arrow(pa.table({\n", " \"source\": pa.array(edge_src, pa.uint64()),\n", " \"target\": pa.array(edge_dst, pa.uint64()),\n", " \"relation\": pa.array([\"similar\"] * len(edge_src)),\n", " \"weight\": pa.array(edge_w, pa.float64()),\n", "}))\n", "links.commit()\n", "session.register(\"doc_links\", links)\n", "print(f\"Edge table: {links.row_count:,} edges, columns={links.columns}\")" ] }, { "cell_type": "markdown", "id": "8f5a98d4", "metadata": {}, "source": [ "### In Process Graph Traversals in SQL\n", "\n", "Now we can run graph traversals directly over our in-memory CSR graph representation with zero network hops:\n", "- `graph_neighbors`: Traverses $N$-hop neighbors.\n", "- `graph_shortest_path`: Computes the shortest connecting path between two concepts.\n", "\n", "Let's query the 2-hop neighborhood around our top lung cancer section:\n" ] }, { "cell_type": "code", "execution_count": 13, "id": "ed00cd07", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:41.701446Z", "iopub.status.busy": "2026-11-22T21:21:41.701311Z", "iopub.status.idle": "2026-11-22T21:21:41.718775Z", "shell.execute_reply": "2026-11-22T21:21:41.718364Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sections within 2 hops of [26067999:ABSTRACT]: 18\n", "\n", " 16422880:DESIGN: Effect of smoking reduction on lung cancer risk.\n", " 17124832:RESULTS: Association between smoking and risk of bladder cancer among men and women.\n", " 24323695:CONCLUSIONS: Pulmonologist involvement, stage-specific treatment, and survival in adults wi\n", " 25121903:ABSTRACT: Cancer treatment and survivorship statistics, 2014.\n", " 26067999:ABSTRACT: Screening for Lung Cancer: U.S. Preventive Services Task Force Recommendation \n", " 32084655:ABSTRACT: Time from finding abnormality on mass-screening to final diagnosis of lung can\n" ] } ], "source": [ "top_id = f\"{int(top['doc_id'])}:{top['section']}\"\n", "top_node = node_of[top_id]\n", "\n", "# Query neighbors within 2 hops of the top retrieved section\n", "nbrs = session.sql(f\"SELECT * FROM graph_neighbors('doc_links', {top_node}, 2)\").to_pandas()\n", "print(f\"Sections within 2 hops of [{top_id}]: {len(nbrs):,}\\n\")\n", "for nid in nbrs[\"node\"].head(6):\n", " sid = label_of.get(int(nid), str(nid))\n", " doc = int(str(sid).split(\":\")[0])\n", " print(f\" {sid}: {title_by_id.get(doc, '')[:78]}\")\n" ] }, { "cell_type": "code", "execution_count": 14, "id": "c18a956c", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:41.720221Z", "iopub.status.busy": "2026-11-22T21:21:41.720088Z", "iopub.status.idle": "2026-11-22T21:21:41.744291Z", "shell.execute_reply": "2026-11-22T21:21:41.743690Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shortest path 10009203:ABSTRACT -> 26067999:ABSTRACT (9 hops, 10 nodes):\n", "\n", "10009203:ABSTRACT -> 4418269:ABSTRACT -> 11254556:ABSTRACT -> 10790846:ABSTRACT -> 8460275:ABSTRACT -> 3831884:ABSTRACT -> 4959368:ABSTRACT -> 17163294:BACKGROUND -> 17163294:RESULTS -> 26067999:ABSTRACT\n" ] } ], "source": [ "src = node_ids[0]\n", "\n", "# Compute shortest path between node_ids[0] and our top retrieved section\n", "path = session.sql(f\"SELECT * FROM graph_shortest_path('doc_links', {src}, {top_node})\").to_pandas()\n", "\n", "num_hops = max(0, len(path) - 1)\n", "print(f\"Shortest path {label_of.get(src, src)} -> {top_id} ({num_hops} hops, {len(path)} nodes):\\n\")\n", "print(\" -> \".join(label_of.get(int(n), str(n)) for n in path[\"node\"].tolist()))" ] }, { "cell_type": "markdown", "id": "f84df5f3", "metadata": {}, "source": [ "## Step 7: Graph RAG in Action: Guiding Retrieval with Subgraph Expansion\n", "\n", "Now we connect our two tables for hybrid Graph RAG retrieval:\n", "1. **Seed Discovery:** Dense vector search finds the top-$K$ section nodes closest to the user's question.\n", "2. **Topological Expansion:** The engine traverses outward from those seeds along `doc_links` edges, extracting an induced 2-hop subgraph.\n", "3. **Relevance Ranking via Personalized PageRank:** By default in local mode, the engine executes in-engine Personalized PageRank (PPR) rooted at the seed nodes with damping factor $\\alpha=0.85$ (continuation probability 0.85, teleportation probability 0.15) to rank induced entities by network authority relative to query seeds.\n", "\n", "BenoDB implements this pipeline directly on the table via **`doc_chunks.graph_rag_search(mode=\"local\")`** (see `Table.graph_rag_search` in [`python/benodb/__init__.py:1723`](https://github.com/benolabsai/benodb/blob/main/python/benodb/__init__.py) and the [Graph RAG & Edge Tables Guide](https://www.benolabsai.com/docs/guides/graph_rag_edge_tables.html)). Under `mode=\"local\"`, the engine traverses the $N$-hop neighborhood around vector seeds, executes Personalized PageRank (`alpha=0.85`) across the extracted subgraph to score entities, and formats the ranked context into prompt-ready markdown for an LLM in a single call:" ] }, { "cell_type": "code", "execution_count": 15, "id": "eeaef7d1", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:41.745575Z", "iopub.status.busy": "2026-11-22T21:21:41.745428Z", "iopub.status.idle": "2026-11-22T21:21:41.987745Z", "shell.execute_reply": "2026-11-22T21:21:41.987237Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mode=local seeds=[7379, 3947, 7376, 503]\n", "nodes=124 edges=510 paths=1\n" ] } ], "source": [ "result = doc_chunks.graph_rag_search(\n", " query=qvec,\n", " edge_table=links,\n", " doc_table=doc_chunks,\n", " id_column=\"section_node\",\n", " vector_column=\"embedding\",\n", " mode=\"local\",\n", " top_k=5,\n", " hops=2,\n", " alpha=0.85, # In-engine Personalized PageRank damping factor (default: alpha=0.85)\n", ")\n", "print(f\"mode={result.mode} seeds={result.seeds}\")\n", "print(f\"nodes={len(result.nodes)} edges={len(result.edges)} paths={len(result.paths)}\")" ] }, { "cell_type": "code", "execution_count": 16, "id": "221f2153", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:41.989206Z", "iopub.status.busy": "2026-11-22T21:21:41.989069Z", "iopub.status.idle": "2026-11-22T21:21:42.007298Z", "shell.execute_reply": "2026-11-22T21:21:42.006615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "### Graph RAG Context (Mode: local)\n", "\n", "#### Discovered Entities (Ranked by Relevance)\n", "- [Node 26067999] (Score: 0.0757): Other risk factors include specific occupational exposures, radon exposure, family history, and history of pulmonary fibrosis or chronic obstructive lung disease. The incidence of lung cancer is relatively low in persons younger than 50 years but increases with age, especially after age 60 years....\n", "- [Node 26067999] (Score: 0.0757): Annual LDCT screening may not be useful for patients with life-limiting comorbid conditions or poor functional status who may not be candidates for surgery. Other Approaches to Prevention Smoking cessation is the most important intervention to prevent NSCLC. Advising smokers to stop smoking and p...\n", "- [Node 26067999] (Score: 0.0757): Benefits of Detection and Early Treatment Although lung cancer screening is not an alternative to smoking cessation, the USPSTF found adequate evidence that annual screening for lung cancer with LDCT in a defined population of high-risk persons can prevent a substantial number of lung cancerrelat...\n", "- [Node 26067999] (Score: 0.0757): Lung cancer has a poor prognosis, and nearly 90% of persons with lung can\n" ] } ], "source": [ "ctx_text = result.format_context()\n", "print(ctx_text[:1200])" ] }, { "cell_type": "markdown", "id": "ef853d2a", "metadata": {}, "source": [ "### Generating Grounded Answers with Retrieved-Document Citations\n", "\n", "We pass the formatted Graph RAG context to an LLM, prompting it to answer the question and cite the exact node IDs retrieved from our lakehouse table.\n", "\n", "*(Note: If an `OPENROUTER_API_KEY` is not configured in your environment, `generate()` returns an explicitly labeled deterministic demonstration fixture so the tutorial executes end-to-end without crashing.)*\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "12391536", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:42.008727Z", "iopub.status.busy": "2026-11-22T21:21:42.008544Z", "iopub.status.idle": "2026-11-22T21:21:42.499820Z", "shell.execute_reply": "2026-11-22T21:21:42.499256Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Configured endpoint: https://openrouter.ai/api/v1\n", "Target model: google/gemma-4-26b-a4b-it\n", "Notice: No OPENROUTER_API_KEY provided \u2014 running in deterministic fallback mode.\n" ] } ], "source": [ "import os\n", "from openai import OpenAI\n", "\n", "# OpenRouter Configuration\n", "OPENROUTER_API_KEY = os.environ.get(\"OPENROUTER_API_KEY\") or \"YOUR_API_KEY_HERE\"\n", "OPENROUTER_BASE_URL = os.environ.get(\"OPENROUTER_BASE_URL\", \"https://openrouter.ai/api/v1\")\n", "\n", "# Explicitly use Google Gemma 4 26B\n", "LLM_MODEL = \"google/gemma-4-26b-a4b-it\"\n", "\n", "llm = OpenAI(\n", " base_url=OPENROUTER_BASE_URL,\n", " api_key=OPENROUTER_API_KEY,\n", " default_headers={\n", " \"HTTP-Referer\": \"https://github.com/benolabsai/benodb\",\n", " \"X-Title\": \"BenoDB Graph RAG\",\n", " }\n", ")\n", "\n", "print(f\"Configured endpoint: {OPENROUTER_BASE_URL}\")\n", "print(f\"Target model: {LLM_MODEL}\")\n", "if OPENROUTER_API_KEY == \"YOUR_API_KEY_HERE\":\n", " print(\"Notice: No OPENROUTER_API_KEY provided \u2014 running in deterministic fallback mode.\")\n", "else:\n", " print(\"API Key detected. Live calls enabled.\")\n" ] }, { "cell_type": "code", "execution_count": 18, "id": "38e68580", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:42.501090Z", "iopub.status.busy": "2026-11-22T21:21:42.500887Z", "iopub.status.idle": "2026-11-22T21:21:42.505065Z", "shell.execute_reply": "2026-11-22T21:21:42.504556Z" } }, "outputs": [], "source": [ "def generate(prompt, system=\"Answer only from the provided context.\",\n", " max_tokens=600, temperature=0.1, model=None):\n", " \"\"\"\n", " Executes live text generation via OpenRouter with automatic provider compatibility.\n", " When running without an active OPENROUTER_API_KEY, returns deterministic demonstration fixtures.\n", " \"\"\"\n", " use_model = model or LLM_MODEL\n", " current_key = os.environ.get(\"OPENROUTER_API_KEY\") or OPENROUTER_API_KEY\n", "\n", " # Offline demonstration mode when no API key is configured\n", " if not current_key or current_key == \"YOUR_API_KEY_HERE\":\n", " print(\"[Execution Source: Offline Demonstration Fixture]\")\n", " if \"research theme\" in prompt.lower():\n", " if \"malaria\" in prompt.lower() or \"africa\" in prompt.lower() or \"phlebotomine\" in prompt.lower():\n", " return \"The shared research theme is the epidemiology, diagnosis, vector biology, and integrated control strategies for malaria and parasitic diseases in Africa.\"\n", " elif \"cdd\" in prompt.lower() or \"yeast\" in prompt.lower() or \"fantom\" in prompt.lower():\n", " return \"The shared research theme is open-source bioinformatics tools, curated genomic databases, and computational platforms for molecular and cellular biology research.\"\n", " else:\n", " return \"The shared research theme is biological and biomedical experimental methodologies, with topics spanning molecular diagnostics, epidemiological surveillance, and genomic resources.\"\n", " elif \"smoking\" in prompt.lower() or \"lung cancer\" in prompt.lower():\n", " return (\n", " '1. Doc 26067999 states: \"The most important risk factor for lung cancer is smoking, which results in approximately 85% of all U.S. lung cancer cases.\"\\n\\n'\n", " '2. Doc 7639744 provides empirical evidence that \"Continued smoking was associated with a significantly increased risk of all cause mortality (hazard ratio 2.94, 95% confidence interval 1.15 to 7.54) and recurrence (1.86, 1.01 to 3.41) in early stage non-small cell lung cancer.\"\\n\\n'\n", " 'Conclusion: The retrieved evidence confirms that smoking substantially increases both the initial risk and the mortality of lung cancer.'\n", " )\n", " raise ValueError(f\"No offline demo fixture exists for prompt: {prompt[:80]}...\")\n", "\n", " # Live generation mode: surface any provider or network errors\n", " messages = []\n", " if system:\n", " messages.append({\"role\": \"system\", \"content\": system})\n", " messages.append({\"role\": \"user\", \"content\": prompt})\n", "\n", " try:\n", " r = llm.chat.completions.create(\n", " model=use_model,\n", " messages=messages,\n", " max_tokens=max_tokens,\n", " temperature=temperature,\n", " )\n", " except Exception as api_err:\n", " err_str = str(api_err).lower()\n", " # If provider rejects the system role (common on Gemma/Mistral endpoints), retry with merged prompt\n", " if \"system\" in err_str or \"role\" in err_str or \"400\" in err_str:\n", " combined_prompt = f\"{system}\\n\\n{prompt}\" if system else prompt\n", " r = llm.chat.completions.create(\n", " model=use_model,\n", " messages=[{\"role\": \"user\", \"content\": combined_prompt}],\n", " max_tokens=max_tokens,\n", " temperature=temperature,\n", " )\n", " else:\n", " raise\n", "\n", " content = r.choices[0].message.content\n", " if content:\n", " print(f\"[Execution Source: Live Model ({use_model})]\")\n", " return content.strip()\n", " return \"[Empty response from model]\" \n" ] }, { "cell_type": "code", "execution_count": 19, "id": "5e2a3ceb", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:42.506557Z", "iopub.status.busy": "2026-11-22T21:21:42.506432Z", "iopub.status.idle": "2026-11-22T21:21:42.510457Z", "shell.execute_reply": "2026-11-22T21:21:42.509945Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Execution Source: Offline Demonstration Fixture]\n", "Generated Answer:\n", "\n", "1. Doc 26067999 states: \"The most important risk factor for lung cancer is smoking, which results in approximately 85% of all U.S. lung cancer cases.\"\n", "\n", "2. Doc 7639744 provides empirical evidence that \"Continued smoking was associated with a significantly increased risk of all cause mortality (hazard ratio 2.94, 95% confidence interval 1.15 to 7.54) and recurrence (1.86, 1.01 to 3.41) in early stage non-small cell lung cancer.\"\n", "\n", "Conclusion: The retrieved evidence confirms that smoking substantially increases both the initial risk and the mortality of lung cancer.\n", "\n", "--- Retrieved-Document Citation Check ---\n", "Cited in Answer: [7639744, 26067999]\n", "Retrieved in Context Window: [4828631, 7639744, 12145359, 14118484, 16422880, 17124832, 24323695, 26067999]\n", "Retrieved Document IDs Present: 2 / 2\n", "Retrieved-Document Citation Check: PASS (all cited document IDs appear in the retrieved context).\n" ] } ], "source": [ "import re\n", "\n", "prompt = f\"\"\"Use ONLY the context below to answer the question.\n", "Cite the PubMed Document IDs (e.g. Doc 26067999, Doc 7639744) you rely on. If the context is insufficient, say so.\n", "\n", "Question: {query}\n", "\n", "Context:\n", "{ctx_text}\n", "\"\"\"\n", "\n", "answer = generate(prompt)\n", "print(\"Generated Answer:\\n\")\n", "print(answer)\n", "\n", "# Programmatic Citation ID Validation\n", "cited_raw = set(re.findall(r\"\\bDoc\\s+(\\d+)\\b|\\bdoc_id[=:\\s]+(\\d+)\\b\", answer))\n", "cited_ids = {int(x) for tup in cited_raw for x in tup if x}\n", "context_doc_ids = set(int(m.group(1)) for m in re.finditer(r\"\\[(?:Node|doc_id)[=\\s]+(\\d+)\\]\", ctx_text))\n", "\n", "valid_citations = cited_ids.intersection(context_doc_ids)\n", "hallucinated_citations = cited_ids - context_doc_ids\n", "\n", "print(\"\\n--- Retrieved-Document Citation Check ---\")\n", "print(f\"Cited in Answer: {sorted(cited_ids)}\")\n", "print(f\"Retrieved in Context Window: {sorted(context_doc_ids)}\")\n", "print(f\"Retrieved Document IDs Present: {len(valid_citations)} / {len(cited_ids)}\")\n", "assert len(cited_ids) > 0, \"Citation check failed: no document citations were produced in the generated answer.\"\n", "assert not hallucinated_citations, f\"Hallucinated citations detected: {hallucinated_citations}\" \n", "print(\"Retrieved-Document Citation Check: PASS (all cited document IDs appear in the retrieved context).\")\n" ] }, { "cell_type": "markdown", "id": "00fdedf6", "metadata": {}, "source": [ "> \ud83d\udcd6 **Dive Deeper:** To explore relationship edge table schemas, in-memory CSR compilation in Rust, and multi-hop graph retrieval patterns, see the [Graph RAG & Edge Tables Guide](https://www.benolabsai.com/docs/guides/graph_rag_edge_tables.html).\n" ] }, { "cell_type": "markdown", "id": "853075ae", "metadata": {}, "source": [ "## Step 8: Global Corpus Understanding: Louvain Community Detection\n", "\n", "Local Graph RAG answers specific questions like *\"does X cause Y?\"* But what if an executive or lead researcher asks a high-level exploratory question:\n", "$$\\text{\"What are the major research themes across our entire dataset?\"}$$\n", "\n", "Top-$K$ retrieval alone is insufficient for this\u2014it only looks at local neighbors. Instead, we run an analogous global community analysis workflow using **Louvain community detection** over our in-memory CSR graph representation compiled from `scifact_links` to partition the corpus into modular clusters:\n", "\n", "> **Note on Community Granularity:** Because the inferred similarity graph is constructed using top-5 nearest neighbors across section centroids, Louvain partitions the graph into many fine-grained, localized modular clusters (the largest community here contains 58 sections out of 8,075 (community partitions vary slightly across runs due to Louvain's stochastic node traversal order)). This step illustrates how global community aggregation queries operate over the compiled CSR topology, rather than presenting a curated corpus-wide topic ontology." ] }, { "cell_type": "code", "execution_count": 20, "id": "d871cc0f", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:42.511660Z", "iopub.status.busy": "2026-11-22T21:21:42.511532Z", "iopub.status.idle": "2026-11-22T21:21:42.557707Z", "shell.execute_reply": "2026-11-22T21:21:42.557103Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Partitioned 8,075 sections into 1,256 Louvain communities\n", "\n", "Largest community contains 58 sections. Sample titles:\n", " 1173667:ABSTRACT: Ranking of elimination feasibility between malaria-endemic countries\n", " 1215116:ABSTRACT: \u201cRapid-Impact Interventions\u201d: How a Policy of Integrated Control for Africa's \n", " 13162391:ABSTRACT: Funnel trap for the capture of phlebotomine sand flies (Diptera: Psychodidae) \n", " 1349033:ABSTRACT: Advantages of larval control for African malaria vectors: Low mobility and beh\n", " 13938878:ABSTRACT: Clinical algorithms for malaria diagnosis lack utility among people of differe\n", " 13959707:BACKGROUND: The Ratio of Monocytes to Lymphocytes in Peripheral Blood Correlates with Incr\n" ] } ], "source": [ "comms = links.louvain_communities(resolution=1.0).to_pandas()\n", "print(f\"Partitioned {len(section_ids):,} sections into {len(comms):,} Louvain communities\")\n", "\n", "largest = max(comms[\"community\"], key=len)\n", "print(f\"\\nLargest community contains {len(largest):,} sections. Sample titles:\")\n", "for nid in sorted(list(largest))[:6]:\n", " sid = label_of.get(int(nid), str(nid))\n", " doc = int(str(sid).split(\":\")[0])\n", " print(f\" {sid}: {title_by_id.get(doc, '')[:78]}\")" ] }, { "cell_type": "markdown", "id": "138cdf19", "metadata": {}, "source": [ "We sample paper titles from the largest cluster and prompt the LLM to synthesize the shared research theme\u2014a lightweight workflow inspired by global community analysis in systems like Microsoft's GraphRAG ([Edge et al., 2024](https://arxiv.org/abs/2404.16130)).\n", "\n", "*(Note: When running without an external LLM API key, `generate()` returns an explicitly labeled deterministic demonstration fixture.)*" ] }, { "cell_type": "code", "execution_count": 21, "id": "5f222cf9", "metadata": { "execution": { "iopub.execute_input": "2026-11-22T21:21:42.558970Z", "iopub.status.busy": "2026-11-22T21:21:42.558816Z", "iopub.status.idle": "2026-11-22T21:21:42.561850Z", "shell.execute_reply": "2026-11-22T21:21:42.561360Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Theme of largest community:\n\n", "[Execution Source: Offline Demonstration Fixture]\n", "The shared research theme is the epidemiology, diagnosis, vector biology, and integrated control strategies for malaria and parasitic diseases in Africa.\n" ] } ], "source": [ "sample = []\n", "for nid in sorted(list(largest))[:15]:\n", " sid = label_of.get(int(nid), \"\")\n", " if sid:\n", " sample.append(title_by_id.get(int(sid.split(\":\")[0]), \"\"))\n", "\n", "theme_prompt = (\n", " \"These are titles of related scientific papers. In one sentence, \"\n", " \"name the shared research theme.\\n\\n\"\n", " + \"\\n\".join(f\"- {t}\" for t in sample if t)\n", ")\n", "\n", "print(\"Theme of largest community:\\n\")\n", "print(generate(theme_prompt, system=\"You are a research analyst.\", max_tokens=1000))" ] }, { "cell_type": "markdown", "id": "b9354e84", "metadata": {}, "source": [ "## Production Scoping & Verified Benchmarks\n", "\n", "### Developer Preview Scope (>= v0.17.1)\n", "BenoDB is currently designed as an embedded Python library and standalone Flight SQL query service for single-node execution over local and cloud lakehouse storage.\n", "- **In Scope for >= v0.17.1:** In process vector ANN search (HNSW), full-text retrieval (BM25), CSR graph traversals, pgvector-compatible operators in DataFusion SQL (`<=>`, `<->`, `<#>`), and GPU acceleration (Apple Metal, NVIDIA CUDA, Intel/AMD WGPU).\n", "- **Out of Scope for >= v0.17.1:** Distributed multinode consensus, distributed sharding, and cross-table multi-statement transactions.\n", "\n", "### Reconstructible Index Sidecars\n", "Primary table data (text, metadata, embeddings) is stored in standard, immutable Parquet files governed by the Apache Iceberg table format. Secondary retrieval indexes (HNSW vector graphs and BM25 postings) are stored as advisory sidecar artifacts. Graph relationships reside in the independently committed Iceberg edge table (scifact_links), which the engine compiles into an in-memory CSR representation for graph traversals and community detection. If an index sidecar is removed or deleted, the engine gracefully falls back to Parquet scans, and indexes can be reconstructed in-place without data loss.\n", "\n", "### Stress Testing & Multi-Writer OCC\n", "Benchmarks published in the project repository ([`benchmarks/results/BENCHMARK_REPORT.md`](https://github.com/benolabsai/benodb/blob/main/benchmarks/results/BENCHMARK_REPORT.md)) and the [Benchmarking Guide](https://www.benolabsai.com/docs/guides/benchmarking.html) demonstrate engine stability under high concurrency:\n", "- **Continuous Ingestion:** 10-minute (600s) continuous write, compaction, and vacuum churn runs stabilized between 4.6\u20135.3 GB peak RSS with zero row loss.\n", "- **Optimistic Concurrency Control (OCC):** Verified zero lost updates across 16 concurrent writers executing 8,111 commit operations in 60 seconds.\n", "- **Crash Recovery:** Sub-5ms state restoration to the last consistent atomic snapshot upon process aborts." ] }, { "cell_type": "markdown", "id": "10f413f8", "metadata": {}, "source": [ "## Architecture Flow\n", "\n", "![BenoDB Graph RAG Architecture Flow](architecture_flow.svg)\n", "\n", "
\n", "View Mermaid Flowchart Source\n", "\n", "```mermaid\n", "flowchart TD\n", " classDef table fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e;\n", " classDef sidecar fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f;\n", " classDef compute fill:#f3f4f6,stroke:#4b5563,stroke-width:1.5px,color:#1f2937;\n", " classDef agent fill:#ecfdf5,stroke:#059669,stroke-width:2px,color:#064e3b;\n", "\n", " subgraph Ingestion [\"1. Document Ingestion & Edge Derivation\"]\n", " A[\"Raw Research Abstracts
(SciFact Corpus)\"]:::compute --> B[\"Section-Aware Chunking
(~80 words)\"]:::compute\n", " B --> C[\"Dense Embeddings
(BGE-Large, 1024-d)\"]:::compute\n", " C --> D[(\"doc_chunks
(Apache Iceberg Table)\")]:::table\n", " \n", " %% Edge Derivation\n", " C --> E1[\"Section Vector Pooling
(Mean Embeddings)\"]:::compute\n", " E1 --> E2[\"Pairwise Top-K Similarity
(bdb.cdist)\"]:::compute\n", " E2 --> E3[(\"doc_links
(Apache Iceberg Edge Table)\")]:::table\n", " end\n", " \n", " subgraph Indexing [\"2. Dual-Table Lakehouse Indexing\"]\n", " D --> F1[\"HNSW Vector Index
(Puffin Sidecar)\"]:::sidecar\n", " D --> F2[\"BM25 Text Index
(Puffin Sidecar)\"]:::sidecar\n", " E3 --> G[\"In-Memory CSR Graph Representation
(Vectorized Adjacency)\"]:::compute\n", " end\n", " \n", " subgraph Retrieval [\"3. Dual Retrieval Workflows\"]\n", " H[\"Agent Query\"]:::agent --> F1\n", " H --> F2\n", " \n", " %% Branch A: Hybrid Passage Retrieval\n", " F1 --> I[\"In Process Hybrid RRF Fusion\"]:::compute\n", " F2 --> I\n", " I --> J[\"Top-K Passage Hits
(Lexical + Vector)\"]:::compute\n", " \n", " %% Branch B: Vector-Seeded Graph RAG\n", " F1 --> K1[\"Dense Vector Seed Discovery
(doc_chunks.graph_rag_search)\"]:::compute\n", " K1 --> K2[\"Local Subgraph Expansion & PPR
(alpha=0.85, 2 hops)\"]:::compute\n", " G --> K2\n", " end\n", " \n", " K2 --> L[\"LLM Context Assembly\"]:::compute\n", " L --> M[\"Cited Response Generation\"]:::agent\n", "```\n", "
\n" ] }, { "cell_type": "markdown", "id": "61e3bd46", "metadata": {}, "source": [ "## The BenoDB Architecture Series\n", "\n", "Continue exploring the architecture, systems mechanics, and connectors of BenoDB:\n", "\n", "- **Article 1 (Current):** *Building Hybrid Retrieval on Your Existing Iceberg Data* \u2014 End-to-end vector, keyword, and graph traversal in a single in process engine.\n", "- **Article 2 (Upcoming):** *Bring Your Own Iceberg: Zero-ETL Lakehouse Search over Existing Tables* \u2014 Layer secondary vector, BM25, and CSR indexes onto existing Iceberg tables in detached overlay mode with zero upstream writes.\n", "- **Article 3 (Upcoming):** *Out of Core Scale: Why Codes-First SIMD Streaming Dominates Disk Graphs at 100M* \u2014 Systems architecture and verified benchmarks under strict memory limits.\n", "- **The Connector Series:**\n", " - *Tier 1: Native Embedded Protocols* \u2014 Arrow Flight SQL, Search REST Gateway, Model Context Protocol (MCP), and `dbt-benodb`.\n", " - *Tier 2: External Enterprise Federation Bridges* \u2014 Apache Spark DSv2 and Trino federation bridge for brownfield enterprise lakehouses.\n", "\n", "> \ud83d\udcec **Get Notified:** Article 2 is currently in preparation. To be notified when it drops, subscribe to updates on the [BenoLabs landing page](https://www.benolabsai.com/#contact) or star the repository on [GitHub](https://github.com/benolabsai/benodb).\n", "\n", "---\n", "\n", "### What to Try Next\n", "\n", "#### 1. Install or Build BenoDB\n", "BenoDB accelerates vector distance operations on **Apple Silicon (Metal)**, **NVIDIA (CUDA 11/12/13, RTX 20\u201350 series / Blackwell)** on Linux and Windows (WSL2 tested; native Windows untested in CI), and **Intel/AMD (WGPU)** (tested on Intel integrated graphics; AMD testers welcome!), with automatic CPU SIMD fallback. For full driver and backend configuration, see the [GPU Setup Guide](https://github.com/benolabsai/benodb/blob/main/docs/GPU_SETUP_GUIDE.md).\n", "\n", "```bash\n", "# Option A: Install from PyPI (auto-detects Metal, CUDA, WGPU, and CPU)\n", "pip install benodb\n", "\n", "# Option B: Build from source with Maturin (requires Rust toolchain)\n", "git clone https://github.com/benolabsai/benodb.git\n", "cd benodb\n", "pip install maturin\n", "maturin develop --release # Apple Metal (macOS), WGPU (AMD/Intel), CPU\n", "maturin develop --release --features cuda # NVIDIA CUDA (Pascal through Blackwell)\n", "```\n", "\n", "#### 2. Run the Notebook\n", "Clone the repository and run this tutorial notebook end-to-end:\n", "\n", "```bash\n", "git clone https://github.com/benolabsai/benodb.git\n", "cd benodb/notebooks\n", "jupyter notebook graph_rag_howto.ipynb\n", "```\n", "\n", "#### 3. Bring Your Own Corpus\n", "Test BenoDB on your Markdown documentation, research PDFs, or domain-specific datasets. Layer indexes directly onto your Parquet data and inspect retrieval with standard SQL.\n", "\n", "#### 4. Explore the Documentation Hub\n", "For full architecture specs, API references, and deployment guides, visit the official documentation at **[benolabsai.com/docs](https://www.benolabsai.com/docs/)**:\n", "- **[Python Vector API Reference](https://www.benolabsai.com/docs/guides/python_vector_api.html)** \u2014 Table schemas, `hybrid_search`, and index configuration.\n", "- **[pgvector SQL Guide](https://www.benolabsai.com/docs/guides/pgvector_sql_guide.html)** \u2014 Reference for PostgreSQL-compatible `<=>`, `<->`, `<#>` operators in DataFusion SQL.\n", "- **[Lakehouse Storage & Iceberg Architecture](https://www.benolabsai.com/docs/guides/architecture.html)** \u2014 Parquet layout, Puffin sidecars, and out-of-core memory discipline.\n", "- **[Graph RAG & Edge Tables](https://www.benolabsai.com/docs/guides/graph_rag_edge_tables.html)** \u2014 Graph schemas, CSR matrices, PageRank, and Louvain algorithms.\n", "- **[GPU Hardware Setup Guide](https://www.benolabsai.com/docs/guides/gpu_setup_guide.html)** \u2014 Drivers and configuration for Apple Silicon (Metal), NVIDIA CUDA, and WGPU.\n", "- **[Concurrency & Benchmarking Reports](https://www.benolabsai.com/docs/guides/benchmarking.html)** \u2014 Stress tests, 16-writer OCC guarantees, and crash recovery.\n", "\n", "#### 5. Audit Lakehouse Interoperability\n", "Query your generated tables using DuckDB, Trino, or Apache Spark to verify open lakehouse access.\n", "\n", "#### 6. Contribute Feedback\n", "Join discussions or report issues on [GitHub Discussions](https://github.com/benolabsai/benodb/discussions) or the [Issue Tracker](https://github.com/benolabsai/benodb/issues).\n", "\n", "---\n", "\n", "*BenoDB is an open-source hybrid vector+graph database on Apache Iceberg. [Official Documentation](https://www.benolabsai.com/docs/) | [GitHub](https://github.com/benolabsai/benodb)*\n" ] }, { "cell_type": "markdown", "id": "f44ca0ce", "metadata": {}, "source": [ "## References\n", "\n", "- Albright & Zhu (2026). *Unsupervised SEC Form 4 Footnote Change Detection Using Fine-Tuned Sentence Transformer and Multi-task LSTM Networks.* Advances and Trends in Artificial Intelligence. Theory and Applications. Springer LNCS. [doi:10.1007/978-981-92-2888-1_12](https://link.springer.com/chapter/10.1007/978-981-92-2888-1_12)\n", "- Lewis et al. (2020). *Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.* Advances in Neural Information Processing Systems 33 (NeurIPS 2020). [papers.nips.cc](https://papers.nips.cc/paper/2020/hash/6b493230205f780e1bc26945df7481e5-Abstract.html)\n", "- Pan et al. (2024). *Unifying Large Language Models and Knowledge Graphs: A Roadmap.* IEEE Transactions on Knowledge and Data Engineering. [doi:10.1109/TKDE.2024.3352100](https://doi.org/10.1109/TKDE.2024.3352100)\n", "- Gao et al. (2023). *Retrieval-Augmented Generation for Large Language Models: A Survey.* arXiv preprint. [arXiv:2312.10997](https://arxiv.org/abs/2312.10997)\n", "- Edge et al. (2024). *From Local to Global: A Graph RAG Approach to Query-Focused Summarization.* Microsoft Research. [arXiv:2404.16130](https://arxiv.org/abs/2404.16130)\n", "- Guti\u00e9rrez et al. (2024). *HippoRAG: Neurobiologically Inspired Long-Term Memory for Large Language Models.* NeurIPS 2024. [arXiv:2405.14831](https://arxiv.org/abs/2405.14831)\n", "- Hogan et al. (2021). *Knowledge Graphs.* ACM Computing Surveys 54(4). [doi:10.1145/3447772](https://doi.org/10.1145/3447772)\n", "- Malkov & Yashunin (2018). *Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs.* IEEE Transactions on Pattern Analysis and Machine Intelligence 42(4). [doi:10.1109/TPAMI.2018.2889473](https://doi.org/10.1109/TPAMI.2018.2889473)\n", "- Robertson & Zaragoza (2009). *The Probabilistic Relevance Framework: BM25 and Beyond.* Foundations and Trends in Information Retrieval. [doi:10.1561/1500000019](https://doi.org/10.1561/1500000019)\n", "- Cormack, Clarke & Buettcher (2009). *Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods.* SIGIR. [doi:10.1145/1571941.1572114](https://doi.org/10.1145/1571941.1572114)\n", "- Traag, Waltman & van Eck (2019). *From Louvain to Leiden: guaranteeing well-connected communities.* Scientific Reports. [doi:10.1038/s41598-019-41695-z](https://doi.org/10.1038/s41598-019-41695-z)\n", "- Apache Software Foundation. *Apache Iceberg Table Spec.* [iceberg.apache.org/spec](https://iceberg.apache.org/spec/)\n" ] }, { "cell_type": "markdown", "id": "6476785c", "metadata": {}, "source": [ "## About the Author\n", "\n", "Rick Albright has worked in capital markets data systems engineering and financial platform architecture for over 35 years, designing large-scale quantitative infrastructure and predictive models for institutional investors. He holds an MS in Investment Management from Pace University, an MS in Analytics from Georgia Tech, and is a PhD candidate in Computer Science at Florida Atlantic University, concentrating on empirical machine learning and large-scale data systems.\n", "\n", "During his published research on corporate insider trading disclosures ([Albright & Zhu, Springer 2026](https://link.springer.com/chapter/10.1007/978-981-92-2888-1_12))\u2014analyzing over 3.3 million SEC Form 4 filings spanning two decades\u2014he confronted the severe operational friction of synchronizing identical research datasets across relational databases, raw array dumps, and search engines. That fragmentation led him to build **[BenoDB](https://github.com/benolabsai/benodb)**: an embedded in process engine that unifies vector search, BM25 text retrieval, and graph analytics directly over open Apache Iceberg tables without external daemons or proprietary storage formats. He develops BenoDB as an open-source project and publishes lakehouse systems research at [Beno Labs](https://www.benolabsai.com)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.4" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": { "1b3634eef7bc47219e907b67d75b5bd8": { "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "model_name": "LayoutModel", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "3eb8702c1e7b468d8f38bc0f2f45fbaf": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "HTMLModel", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "HTMLView", "description": "", "description_allow_html": false, "layout": "IPY_MODEL_d645fb91d42c4b93a8576e3b43257b12", "placeholder": "\u200b", "style": "IPY_MODEL_a48a22c1b0db4fd2b00d2b9771a99921", "tabbable": null, "tooltip": null, "value": "Loading\u2007weights:\u2007100%" } }, "669f7cbd6b9f48feafb64aac787fa40b": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "HTMLStyleModel", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "StyleView", "background": null, "description_width": "", "font_size": null, "text_color": null } }, "8a64deec91134732826ca04e24720cbf": { "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "model_name": "LayoutModel", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "a48a22c1b0db4fd2b00d2b9771a99921": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "HTMLStyleModel", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "StyleView", "background": null, "description_width": "", "font_size": null, "text_color": null } }, "bfe222dc6ae646128fc74e4b3f8a77b7": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "ProgressStyleModel", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "c1a06278ab604d67b07412f053b5d93b": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "FloatProgressModel", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_allow_html": false, "layout": "IPY_MODEL_1b3634eef7bc47219e907b67d75b5bd8", "max": 391.0, "min": 0.0, "orientation": "horizontal", "style": "IPY_MODEL_bfe222dc6ae646128fc74e4b3f8a77b7", "tabbable": null, "tooltip": null, "value": 391.0 } }, "cf8623e105c649188b53e0d3b0a5690e": { "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "model_name": "LayoutModel", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "d645fb91d42c4b93a8576e3b43257b12": { "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "model_name": "LayoutModel", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "e18985bfc66442918d41e8135abf1b64": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "HTMLModel", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "HTMLView", "description": "", "description_allow_html": false, "layout": "IPY_MODEL_8a64deec91134732826ca04e24720cbf", "placeholder": "\u200b", "style": "IPY_MODEL_669f7cbd6b9f48feafb64aac787fa40b", "tabbable": null, "tooltip": null, "value": "\u2007391/391\u2007[00:00<00:00,\u20079930.02it/s]" } }, "f792556cb5314eaab6e2c89c7c9b4afc": { "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "model_name": "HBoxModel", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_3eb8702c1e7b468d8f38bc0f2f45fbaf", "IPY_MODEL_c1a06278ab604d67b07412f053b5d93b", "IPY_MODEL_e18985bfc66442918d41e8135abf1b64" ], "layout": "IPY_MODEL_cf8623e105c649188b53e0d3b0a5690e", "tabbable": null, "tooltip": null } } }, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 5 }