AiCredits
Budget RAG

Semantic Search on a Budget: Embeddings + SQLite for Small Datasets

Build semantic search over small datasets with SQLite and local embeddings, then rerank and answer with deepseek-v4-flash. No vector database required.

Published 2026-11-23 Updated 2026-11-23 9 min

The vector database you probably don't need yet

Most semantic search tutorials start by asking you to provision a vector database. If your corpus is a support FAQ, an internal handbook, a few hundred product pages, or the docs folder of your own repo, that is a service you will pay for, secure, back up, and keep in sync — to solve a problem a single SQLite file already solves.

The honest engineering position is this: brute-force cosine similarity over a few tens of thousands of chunks is a matrix multiply. SQLite gives you durable storage, transactions, and a query language for the metadata filters you actually care about. Together they cover a surprising amount of ground before you need approximate nearest neighbour indexes.

This post builds the whole thing: schema, embeddings, search, an LLM rerank pass, and answer synthesis. Embeddings run locally on a small open model, so the only metered cost is the chat model — which is where deepseek-v4-flash earns its place.

When SQLite is the right vector store

  • Your chunk count is in the thousands, not millions. Brute force is a linear scan. The moment queries get slow you can measure it yourself in one line instead of guessing.

  • You already filter hard on metadata. Tenant, language, product line, published date. SQL WHERE clauses are free and battle-tested; vector databases make you learn their filter syntax and sometimes their limitations.

  • You want one deployable artifact. A .db file ships with your app, gets copied to a laptop, and works on a plane. No connection strings, no network hop, no cold starts.

  • You are prototyping and hate premature infrastructure. The migration path to a dedicated vector store is straightforward later — the embeddings you stored are portable.

ApproachSetupQuery speedBest forMain drawback
SQLite + numpy dot productOne file, no serviceLinear in chunk countTens of thousands of chunks, single processScores recomputed on every query
SQLite FTS5 (keyword)Built into SQLiteVery fast, indexedExact terms: error codes, SKUs, namesMisses paraphrases and synonyms
FAISS / hnswlib in-processExtra dependency plus index filesApproximate, fast at scale100k+ vectors on one machineIndex rebuild and persistence plumbing
Hosted vector databaseAccount, network hop, ongoing spendLow at scaleMillions of vectors, multi-tenantAnother service to secure and keep in sync

Store vectors as float32 BLOBs, not JSON

This is the single decision that most affects how the whole system feels. A 384-dimension embedding written as JSON costs you thousands of characters per row that have to be parsed on every read. The same vector as a raw float32 BLOB is compact and loads straight into numpy with np.frombuffer — effectively zero-copy.

Normalise on write. If every stored vector has unit length, cosine similarity collapses to a plain dot product, and the search function becomes one line. Do the normalisation at index time, once, instead of at query time, forever.

# pip install sentence-transformers numpy openai
import sqlite3
import numpy as np
from sentence_transformers import SentenceTransformer

DIM = 384  # all-MiniLM-L6-v2 output size
embedder = SentenceTransformer("all-MiniLM-L6-v2")

db = sqlite3.connect("search.db")
db.execute("""
CREATE TABLE IF NOT EXISTS chunks (
    id          INTEGER PRIMARY KEY,
    doc_id      TEXT NOT NULL,
    text        TEXT NOT NULL,
    content_hash TEXT NOT NULL,
    vec         BLOB NOT NULL
)
""")
db.execute("CREATE INDEX IF NOT EXISTS idx_chunks_doc ON chunks(doc_id)")

docs = [
    ("refund-policy", "Refunds are issued within 14 days of purchase if the API key was never used."),
    ("rate-limits",   "Keys are limited to 60 requests per minute by default; contact support to raise it."),
    ("billing",       "Invoices are generated on the first of each month and emailed to the account owner."),
]

rows = []
for doc_id, text in docs:
    vec = embedder.encode(text, normalize_embeddings=True).astype(np.float32)
    rows.append((doc_id, text, str(hash(text)), vec.tobytes()))

db.executemany(
    "INSERT INTO chunks (doc_id, text, content_hash, vec) VALUES (?, ?, ?, ?)",
    rows,
)
db.commit()
print(f"indexed {len(rows)} chunks")

Search: one matrix multiply

Load the vectors once into an (n, dim) matrix, keep it in memory, and score each query with MAT @ q. With normalised vectors and np.argsort, that is the entire retrieval layer. Rebuild the matrix when you re-index; for a few thousand rows that is milliseconds.

The comment worth leaving in your codebase: if this ever gets too slow, you will know because you measured it — not because a blog post told you to install a graph index.

import sqlite3
import numpy as np
from sentence_transformers import SentenceTransformer

embedder = SentenceTransformer("all-MiniLM-L6-v2")

def load_index(path="search.db"):
    db = sqlite3.connect(path)
    ids, texts, blobs = [], [], []
    for cid, text, blob in db.execute("SELECT id, text, vec FROM chunks"):
        ids.append(cid)
        texts.append(text)
        blobs.append(blob)
    db.close()
    matrix = np.vstack([np.frombuffer(b, dtype=np.float32) for b in blobs])
    return np.array(ids), texts, matrix

IDS, TEXTS, MAT = load_index()

def top_k(query: str, k: int = 5):
    q = embedder.encode(query, normalize_embeddings=True).astype(np.float32)
    scores = MAT @ q                       # cosine, because rows are unit length
    order = np.argsort(-scores)[:k]
    return [(float(scores[i]), int(IDS[i]), TEXTS[i]) for i in order]

for score, cid, text in top_k("how long does a refund take"):
    print(f"{score:.3f}  [{cid}] {text[:70]}")

Rerank the top candidates with deepseek-v4-flash

Bi-encoder embeddings are recall machines, not precision machines. They will happily rank a chunk about invoice emails above one that answers the actual question, because both live in the same semantic neighbourhood. The fix is cheap: take the top handful of candidates and let a small LLM order them against the literal question.

Use deepseek-v4-flash here. This is a short, boring classification task over a few hundred tokens of context, and flash is the right tool. Ask for a JSON array of indices, set temperature to zero, and always keep a fallback so a malformed reply degrades to the vector order instead of throwing.

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

def rerank(query: str, candidates: list, keep: int = 3):
    listing = "\n".join(f"[{i}] {c[2]}" for i, c in enumerate(candidates))
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        temperature=0,
        messages=[
            {"role": "system",
             "content": "You rank passages by how directly they answer the question. "
                        "Reply with a JSON array of indices, best first, and nothing else."},
            {"role": "user",
             "content": f"Question: {query}\n\nPassages:\n{listing}"},
        ],
    )
    raw = resp.choices[0].message.content
    try:
        order = [int(i) for i in json.loads(raw)]
        order = [i for i in order if 0 <= i < len(candidates)]
    except (json.JSONDecodeError, TypeError, ValueError):
        order = list(range(len(candidates)))   # graceful fallback
    return [candidates[i] for i in order[:keep]]

Answer synthesis with the same client

Retrieval is half the product. The other half is an answer that cites what it used and admits when the context is thin. Keep the system prompt short, stable, and first in the message list — a stable prefix is what prompt caching rewards, so cached input costs less than fresh input on repeated calls. Retrieved context goes after it, because it changes per query.

def answer(query: str, k: int = 5) -> str:
    hits = rerank(query, top_k(query, k=k))
    context = "\n\n".join(f"(id={cid}) {text}" for _, cid, text in hits)
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        temperature=0.2,
        messages=[
            {"role": "system",
             "content": "Answer using only the provided context. "
                        "Cite chunk ids in square brackets. "
                        "If the context does not contain the answer, say so plainly."},
            {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {query}"},
        ],
    )
    return resp.choices[0].message.content

print(answer("how long do refunds take?"))

Add FTS5 when your users type exact strings

  • Semantic search is bad at identifiers. Error codes, SKUs, function names, and ticket numbers are better served by SQLite's built-in FTS5 index. Run both retrievers and merge.

  • Merge with reciprocal rank fusion: score = sum(1 / (60 + rank)) across each result list. One line of maths, no tuning, no score calibration between two incompatible scales.

  • Store the embedding model name and dimension alongside the vector. When you swap models you can re-embed one shard at a time instead of the whole corpus, and you will never silently mix incompatible spaces.

  • Keep a content_hash column and skip re-embedding rows whose text has not changed. Incremental re-indexing turns a nightly job into an instant one.

What this actually costs

The embeddings are the free part. A small sentence-transformer runs on CPU, produces vectors once, and those vectors live in your database forever. That is why the local-model approach pairs so well with a metered chat API: you spend money only on the calls where a language model genuinely adds value — reranking and answering.

Within the chat calls, the economics are simple. deepseek-v4-flash is the default for reranking and short answers; deepseek-v4-pro costs more and is worth reaching for only when the task needs long-context synthesis or harder reasoning over a big context window. Cache hits are cheaper than fresh tokens, so keep the stable part of your prompt at the front. Off-peak requests cost less than peak. Current rates are always on the pricing page — check aicreditsapi.com/deepseek-prices rather than trusting a number in a blog post, including this one.

If the friction keeping you on a local-only stack is account setup, AiCredits sells DeepSeek API credits to international developers with a card or PayPal, no Chinese phone number or bank account required. Same OpenAI-compatible client, same base_url, one environment variable.

Rule of thumb: don't add a vector database until you can name the specific query that breaks SQLite — and have measured how long it takes.

FAQ

How many chunks can SQLite handle before search gets slow?

Brute force scans every vector, so cost grows linearly with chunk count. For a few tens of thousands of 384-dimension vectors, a single query is still a small matrix multiply on a laptop. Time your own corpus with %timeit top_k("…") before deciding to migrate — the threshold depends on your latency budget and hardware, not on a universal number.

Do the embeddings have to come from the same provider as the chat model?

No. Embeddings and generation are independent. A local sentence-transformer produces the vectors, and deepseek-v4-flash consumes the retrieved text. The only rule is consistency: whatever model you index with, you must query with.

Can I store embeddings as JSON text instead of a BLOB?

You can, but don't. A 384-dimension float32 vector is a small fixed-size binary blob; as JSON it becomes several thousand characters that must be parsed on every read. np.frombuffer on a BLOB is effectively free.

Should I use deepseek-v4-pro for reranking?

Usually not. Reranking is a short classification task with a small candidate list, which is exactly what deepseek-v4-flash is for. Reserve deepseek-v4-pro for answer synthesis over long contexts where the extra reasoning capacity actually changes the output.

How do I re-index when documents change?

Keep a content hash per chunk. On update, compare hashes and only re-embed rows that changed. Store the model name and dimension per row so a model swap can be rolled out shard by shard instead of forcing a full rebuild.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×