DuckDB Vector Search with VSS Extension and Ollama: Lightweight Semantic Search Without a Dedicated Vector DB

AI tutorial - IT technology blog
AI tutorial - IT technology blog

Combining semantic search with analytical SQL usually forces you into an awkward setup. You store structured records in PostgreSQL or DuckDB, push text embeddings into Qdrant or Milvus, and write glue code to keep both systems in sync.

That extra infrastructure rarely pays off on single-node workloads. Whether you are indexing 5,000 support tickets or 2 million log lines, a separate vector database adds network hops, Docker containers, and sync bugs. Running DuckDB vector search directly inside your analytical engine with the official vss extension and Ollama keeps everything in one place.

I have used this stack in production for internal knowledge bases, incident triage tools, and reporting dashboards. Whenever a query needs both GROUP BY aggregations and semantic filtering, keeping vectors next to the rows makes life much simpler.

Quick Start: DuckDB Vector Search in 5 Minutes

Grab Python, the duckdb package, and a local Ollama instance. You can have a working prototype running in a couple of minutes.

1. Install Dependencies and Pull an Embedding Model

Install the Python client libraries and pull nomic-embed-text in Ollama. It outputs 768-dimensional vectors (roughly 3 KB per row as FLOAT[768]) and runs comfortably on CPU.

pip install duckdb requests
ollama pull nomic-embed-text

2. Create a Local Semantic Search Script

This script opens a local DuckDB file, loads the vss extension, fetches embeddings from Ollama’s HTTP API, and ranks matches by cosine distance.

import duckdb
import requests

OLLAMA_URL = "http://localhost:11434/api/embed"
MODEL = "nomic-embed-text"

def get_embedding(text: str) -> list[float]:
    resp = requests.post(OLLAMA_URL, json={"model": MODEL, "input": text}, timeout=30)
    resp.raise_for_status()
    return resp.json()["embeddings"][0]

con = duckdb.connect("analytics_vectors.duckdb")
con.execute("INSTALL vss; LOAD vss;")

con.execute("""
    CREATE TABLE IF NOT EXISTS incidents (
        id INTEGER,
        service VARCHAR,
        severity VARCHAR,
        summary VARCHAR,
        embedding FLOAT[768]
    );
""")

samples = [
    (1, "auth-api", "high", "Users randomly logged out after JWT refresh fails"),
    (2, "billing", "medium", "Stripe webhook timeout during invoice generation"),
    (3, "search", "low", "Slow autocomplete response when filtering by category"),
]

for row_id, service, severity, summary in samples:
    vec = get_embedding(summary)
    con.execute(
        "INSERT INTO incidents VALUES (?, ?, ?, ?, ?)",
        [row_id, service, severity, summary, vec],
    )

query_vec = get_embedding("token expiration kicks users out")
results = con.execute("""
    SELECT id, service, severity, summary,
           array_cosine_distance(embedding, ?::FLOAT[768]) AS distance
    FROM incidents
    ORDER BY distance ASC
    LIMIT 2;
""", [query_vec]).fetchall()

for row in results:
    print(row)

Run the script and DuckDB returns the auth-api JWT incident first. Even though your query said “token expiration” instead of “JWT refresh”, cosine distance still catches the match.

Deep Dive: Why Hybrid SQL + Vector Search Works Better Here

Many teams reach for a dedicated vector store because they assume SQL engines cannot index high-dimensional arrays well. Scanning raw FLOAT[] columns with brute-force cosine distance does slow down past 50,000 rows.

DuckDB closes that gap with the vss (Vector Similarity Search) extension, which embeds the usearch library to build HNSW indexes inside your database. Everything lives in one .duckdb file:

  • Zero sync drift: Inserting, updating, or deleting a row modifies both the metadata columns and the embedding in the same ACID transaction.
  • Fixed-size arrays: DuckDB separates variable-length lists (FLOAT[]) from fixed-size arrays (FLOAT[768]). The vss extension requires FLOAT[N] columns so vector memory stays contiguous and SIMD-friendly.
  • Local privacy with Ollama: Because Ollama listens on localhost:11434, sensitive logs, customer tickets, and internal docs never leave your machine.

Advanced Usage: HNSW Indexing and Hybrid Analytical Queries

Brute-force scans are fine for 5,000 rows, but they lag once your table hits six figures. Attaching an HNSW index to your FLOAT[768] column keeps lookups fast while preserving full SQL support.

Enabling HNSW Index Persistence

DuckDB blocks HNSW indexes on disk-backed databases by default because index persistence is still marked experimental. Enable the flag first, then create the index:

INSTALL vss;
LOAD vss;
SET hnsw_enable_experimental_persistence = true;

CREATE INDEX incidents_hnsw_idx
ON incidents
USING HNSW (embedding)
WITH (metric = 'cosine');

DuckDB’s planner only picks up this index when your ORDER BY expression matches the index metric and includes a LIMIT. For metric = 'cosine', use array_cosine_distance(embedding, ?::FLOAT[768]).

Combining Structured Filters and Aggregations

Standalone vector databases struggle when you want both semantic ranking and relational rollups. In DuckDB, you can pull the top 200 semantic candidates, filter by severity, and aggregate by service in one query:

WITH semantic_matches AS (
    SELECT id, service, severity, summary,
           array_cosine_distance(embedding, ?::FLOAT[768]) AS distance
    FROM incidents
    ORDER BY distance ASC
    LIMIT 200
)
SELECT service, COUNT(*) AS matching_incidents, MIN(distance) AS best_match
FROM semantic_matches
WHERE severity IN ('high', 'medium')
GROUP BY service
ORDER BY best_match ASC;

Batching Ollama Embeddings for Faster Ingestion

Sending one HTTP request per row wastes time on round-trips. Ollama’s /api/embed endpoint accepts a list of strings in input, so batching 64 or 128 texts per call cuts ingestion time dramatically:

def get_embeddings_batch(texts: list[str]) -> list[list[float]]:
    resp = requests.post(
        "http://localhost:11434/api/embed",
        json={"model": "nomic-embed-text", "input": texts},
        timeout=60,
    )
    resp.raise_for_status()
    return resp.json()["embeddings"]

Practical Tips for Running in Production

Running this stack across several internal services taught me a few guardrails worth setting up on day one:

  • Lock your vector dimensions early: nomic-embed-text outputs 768 dimensions, whereas mxbai-embed-large outputs 1024. Switching models later means recreating the FLOAT[N] column and re-embedding every row.
  • Cap memory during index builds: HNSW graphs are built in RAM, often needing 1.2x to 1.5x the raw vector size (around 400–450 MB for 100,000 768-dim rows). Set SET memory_limit = '2GB'; so large rebuilds do not trigger an OOM kill on small VMs.
  • Back up raw data to Parquet: Because HNSW persistence is still experimental in DuckDB, export your text and embeddings to Parquet on a schedule. Rebuilding a fresh database and recreating the index from Parquet takes only seconds.
  • Over-fetch before filtering: DuckDB’s HNSW scan retrieves top-K neighbors before applying post-filters in many query shapes. If a strict WHERE clause trims your results below what you need, fetch a larger LIMIT inside a CTE first.

For single-node workloads, DuckDB’s vss extension paired with Ollama gives you fast semantic search and full SQL analytics with almost no operational overhead.

Share: