Most RAG tutorials stop at the retrieval step — or they start with a hosted vector database that wants an account, an API key, and a credit card before you have written a line of code. Milvus Lite skips all of that: it is the same Milvus engine packaged as a Python library, storing vectors in a folder on your laptop. No server, no Docker, no key. And since the 3.x release, it ships with BM25 full-text search built in, so the hybrid search that usually takes two systems and a synchronization job is a single function call.

This tutorial builds a complete local RAG pipeline with it — embeddings, hybrid search, metadata filters, and a prompt you can hand to any language model — and measures each retrieval method on the same question, so you can see what each one actually contributes. Every command and code block below was run end to end; the outputs shown are the real ones.

What you'll need#

  • Python 3.10 or newer and pip. No GPU, no Docker, no accounts.
  • About 1 GB of free disk — the Python packages (PyTorch plus the embedding model) are the heavy part.
  • 10 minutes. The full script runs in about 10 seconds on CPU once the packages are installed.
  • Versions used here: PyMilvus 3.0.3, Milvus Lite 3.2.2, sentence-transformers 6.3.0, Python 3.12.

Step 1: Install and set up the project#

Create an isolated environment and install the three packages. The milvus-lite extra is what gives PyMilvus its local backend; installing pymilvus alone does not include it.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install "pymilvus[milvus-lite]==3.0.3" "milvus-lite==3.2.2" sentence-transformers

On Windows, name milvus-lite explicitly (as above) because pip skips the extra there. Verify the install before going further:

python -c "import pymilvus; print(pymilvus.__version__)"
# 3.0.3

Step 2: Load the embedding model and encode your documents#

The embedding model turns text into dense vectors. This tutorial uses all-MiniLM-L6-v2 — small, fast on CPU, and a standard default for local RAG. It produces 384-dimensional vectors, a number that matters in the next step because the collection's vector field must declare the same dimension.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
texts = [d["text"] for d in DOCS]
vectors = model.encode(texts, normalize_embeddings=True)
print(vectors.shape)  # (12, 384)

Two details worth getting right. First, normalize_embeddings=True: the collection will use inner-product search, and with normalized vectors inner product equals cosine similarity, so the closest vectors are the most similar in meaning. Second, the corpus. For this tutorial it is twelve short documents about Milvus, retrieval, and RAG — small enough to read, varied enough that the three search methods return visibly different results:

DOCS = [
    {"title": "What Milvus Lite is", "category": "milvus",
     "text": "Milvus Lite is a lightweight local backend for the Milvus Python SDK. It stores vectors in a local directory, needs no server or Docker, and is designed for development and small workloads on a laptop."},
    {"title": "MilvusClient basics", "category": "milvus",
     "text": "MilvusClient is the Python SDK entry point. Pass a local path ending in .db to open a Milvus Lite database, or pass a server URI and token to connect to Milvus Standalone, Distributed, or Zilliz Cloud with the same API."},
    {"title": "Dense vectors and embeddings", "category": "retrieval",
     "text": "A dense vector is a list of floating point numbers that represents the meaning of a piece of text. An embedding model such as all-MiniLM-L6-v2 turns each document into a 384-dimensional vector, and similar meanings land close together in that space."},
    {"title": "Cosine similarity and inner product", "category": "retrieval",
     "text": "Vector search ranks documents by a similarity metric. With normalized embeddings, inner product equals cosine similarity, so the closest vectors are the most similar in meaning. Milvus supports inner product, cosine, and L2 distance."},
    {"title": "BM25 keyword search", "category": "retrieval",
     "text": "BM25 is a classic ranking function for keyword search. It scores documents by how often the query terms appear, adjusted for document length, so exact terms such as product codes and error messages match even when no synonym is involved."},
    {"title": "Reciprocal rank fusion", "category": "retrieval",
     "text": "Reciprocal rank fusion, or RRF, merges ranked lists from different retrievers. Each hit scores one over k plus its rank in each list, with k usually 60, and the scores are summed. No score calibration is needed because only ranks are combined."},
    {"title": "Hybrid search in Milvus", "category": "milvus",
     "text": "Milvus hybrid search runs a dense vector request and a BM25 full-text request in one call and fuses them with RRF or a weighted ranker. The BM25 function builds sparse vectors automatically on insert, so there is no second search engine to keep in sync."},
    {"title": "Chunking documents for RAG", "category": "rag",
     "text": "Retrieval augmented generation works best on short chunks of 100 to 300 words. Split long documents at paragraph or heading boundaries, keep each chunk self-contained, and store the source title with every chunk so the answer can cite it."},
    {"title": "Metadata filtering", "category": "milvus",
     "text": "Milvus collections hold scalar fields alongside vectors, and search requests accept filter expressions such as category equals retrieval. Filters run before the vector search, so multi-tenant rules and access control are enforced inside the query."},
    {"title": "When to use Milvus Standalone", "category": "milvus",
     "text": "Move from Milvus Lite to Milvus Standalone or Distributed when the data no longer fits on one laptop, when several processes must write at once, or when you need authentication, roles, and high availability. The MilvusClient code stays the same; only the connection URI changes."},
    {"title": "Evaluating retrieval quality", "category": "rag",
     "text": "Measure retrieval with recall at k and nDCG on a small set of questions with known good documents. Compare dense-only, BM25-only, and hybrid search on the same questions before choosing a strategy, because the winner depends on the query mix."},
    {"title": "Prompt assembly for RAG", "category": "rag",
     "text": "A RAG answer prompt contains the user question plus the retrieved chunks, each labelled with its source. Instruct the model to answer only from the supplied context and to say it does not know when the context has no answer, which keeps hallucinations down."},
]

For real documents, chunk first: split long files into 100–300-word pieces at paragraph or heading boundaries, keep each chunk self-contained, and store the source title with every chunk so answers can cite it.

Step 3: Create the collection with a BM25 function#

This is the step that makes the tutorial work. The schema declares the usual fields — an auto-generated id, title and category text, the document text, and a 384-dimensional dense vector — plus a sparse vector field and a BM25 Function that fills it automatically from the text field on every insert.

from pymilvus import MilvusClient, DataType, Function, FunctionType

client = MilvusClient("./milvus_rag.db")

schema = client.create_schema()
schema.add_field("id", DataType.INT64, is_primary=True, auto_id=True)
schema.add_field("title", DataType.VARCHAR, max_length=200)
schema.add_field("category", DataType.VARCHAR, max_length=50)
schema.add_field("text", DataType.VARCHAR, max_length=2000, enable_analyzer=True)
schema.add_field("dense", DataType.FLOAT_VECTOR, dim=384)
schema.add_field("sparse", DataType.SPARSE_FLOAT_VECTOR)
schema.add_function(Function(
    name="bm25", input_field_names=["text"],
    output_field_names=["sparse"], function_type=FunctionType.BM25))

index_params = client.prepare_index_params()
index_params.add_index("dense", index_type="AUTOINDEX", metric_type="IP")
index_params.add_index("sparse", index_type="SPARSE_INVERTED_INDEX", metric_type="BM25")

client.create_collection("docs", schema=schema, index_params=index_params)

Three things to notice. enable_analyzer=True on the text field turns on Milvus's built-in text analysis, which tokenizes the text for BM25. The dense index uses AUTOINDEX with inner-product distance, matching the normalized embeddings from Step 2. And in Milvus Lite 3.x, the ./milvus_rag.db path is a directory holding the database files, not a single file — reopen it with the same path later. One process owns a database directory at a time, and concurrent writes to the same collection are not supported, so treat Lite as a single-writer local store.

Diagram of the RAG pipeline: documents become embeddings, are stored in Milvus Lite with vectors and a keyword index, then hybrid search returns a ranked list for the answer
AI-generated illustration: the pipeline this tutorial builds, from documents to a ranked answer.

Step 4: Insert and verify#

Insert the twelve documents. Notice the rows carry no sparse value — the BM25 function computes it from text during the insert:

data = [{"title": d["title"], "category": d["category"], "text": d["text"],
         "dense": vectors[i].tolist()} for i, d in enumerate(DOCS)]
res = client.insert(collection_name="docs", data=data)
print(res["insert_count"])  # 12
print(client.get_collection_stats("docs")["row_count"])  # 12

Both numbers come back as 12, confirming the collection holds every document. From here on, every search in this tutorial runs against this collection.

Step 5: Dense-only search — the baseline#

Start with plain vector search so the later methods have something to beat. Embed the question with the same model, then search the dense field:

query = "How do I combine keyword search and vector search in one query?"
qvec = model.encode([query], normalize_embeddings=True)[0].tolist()

res = client.search(collection_name="docs", data=[qvec],
                    limit=3, output_fields=["title", "category"])
for hit in res[0]:
    print(f"{hit['distance']:.4f}  [{hit['entity']['category']}] {hit['entity']['title']}")
0.4216  [milvus] Metadata filtering
0.4090  [retrieval] Cosine similarity and inner product
0.4077  [milvus] Hybrid search in Milvus

The right document is in the list — third — but the top hit is a near-miss about metadata filtering. Dense search understood the question's meaning, yet with only twelve documents the ranking is noisy: the distances are inner products on normalized vectors, so closer to 1 means more similar, and here the top three sit within 0.014 of each other. Keep that in mind when you read the hybrid result below.

Now the other half: search the sparse field with the raw query text, no embedding involved. Milvus scores it with the BM25 values the function built at insert time:

res = client.search(collection_name="docs", data=[query],
                    anns_field="sparse", limit=3,
                    output_fields=["title", "category"])
for hit in res[0]:
    print(f"{hit['distance']:.4f}  [{hit['entity']['category']}] {hit['entity']['title']}")
-7.4525  [retrieval] BM25 keyword search
-5.6076  [milvus] Hybrid search in Milvus
-5.1160  [milvus] Metadata filtering

BM25 ranks the exact-match document first: the query literally contains the words "keyword search", and the "BM25 keyword search" document contains them too. Two things about the numbers. First, BM25 scores come back negative — Milvus negates the BM25 score to present it as a distance, so the most negative value is the best match; only the order matters. Second, BM25 is blind to meaning: it would rank a document containing the words "vector search" above a better document that says the same thing with different words. That is exactly the gap dense search fills, and why the two belong together.

Step 7: Hybrid search with RRF#

Hybrid search runs both requests in one call and fuses the two ranked lists with reciprocal rank fusion. Each hit scores 1 / (60 + rank) in each list it appears in, and the scores are summed — the smoothing constant 60 is the default. Because only ranks are combined, no score calibration is needed between the two very different scoring systems:

from pymilvus import AnnSearchRequest, RRFRanker

reqs = [AnnSearchRequest([qvec], "dense", {"metric_type": "IP"}, limit=10),
        AnnSearchRequest([query], "sparse", {}, limit=10)]
res = client.hybrid_search(collection_name="docs", reqs=reqs,
                           ranker=RRFRanker(60), limit=3,
                           output_fields=["title", "text", "category"])
for hit in res[0]:
    print(f"{hit['distance']:.4f}  [{hit['entity']['category']}] {hit['entity']['title']}")
0.0323  [milvus] Metadata filtering
0.0320  [milvus] Hybrid search in Milvus
0.0318  [retrieval] BM25 keyword search

The fused top three now contains the best of both methods: the dense list's near-miss, the document that actually answers the question, and the BM25 list's exact match. The two lists disagreed — dense put "Hybrid search in Milvus" third, BM25 put it second — and RRF reconciled them into a single ranked list without you tuning any weights. If you do want to tilt the balance, Milvus also offers a weighted ranker that normalizes each path's scores and applies per-path weights; research cited on Milvus's hybrid search page found weighted fusion beats RRF when you have a small labeled set to tune on.

Illustration of hybrid search: a keyword search path and a semantic search path merging into one ranked list of documents
AI-generated illustration: keyword search and semantic search merge into one ranked list.

Step 8: Add a metadata filter#

Real collections are rarely one flat pile of documents — they have tenants, owners, document types. Each hybrid request can carry its own filter expression, applied before the vector search, so the filter is enforced inside the query rather than by trimming results afterwards:

reqs = [AnnSearchRequest([qvec], "dense", {"metric_type": "IP"}, limit=10,
                         expr="category == 'retrieval'"),
        AnnSearchRequest([query], "sparse", {}, limit=10,
                         expr="category == 'retrieval'")]
res = client.hybrid_search(collection_name="docs", reqs=reqs,
                           ranker=RRFRanker(60), limit=3,
                           output_fields=["title", "text", "category"])
for hit in res[0]:
    print(f"{hit['distance']:.4f}  [{hit['entity']['category']}] {hit['entity']['title']}")
0.0325  [retrieval] Cosine similarity and inner product
0.0325  [retrieval] BM25 keyword search
0.0315  [retrieval] Dense vectors and embeddings

Every result now carries the retrieval category, and the ranking reshuffles accordingly — the filter changes which documents are candidates, not just which ones are displayed. This is the mechanism you would use for per-user or per-tenant scoping in a real app: one collection, one query, with the access rule in the expr.

Step 9: Assemble the RAG prompt and call your model#

Retrieval is done; generation is a handoff. Join the top chunks, each labelled with its source title, into a prompt that tells the model to answer only from the supplied context:

context = "\n\n".join(
    f"[{h['entity']['title']}] {h['entity']['text']}" for h in res[0])
prompt = (
    "Answer the question using only the context below. "
    "If the context does not contain the answer, say so.\n\n"
    f"Context:\n{context}\n\nQuestion: {query}\nAnswer:")
print(prompt)
Answer the question using only the context below. If the context does not contain the answer, say so.

Context:
[Cosine similarity and inner product] Vector search ranks documents by a similarity metric. With normalized embeddings, inner product equals cosine similarity, so the closest vectors are the most similar in meaning. Milvus supports inner product, cosine, and L2 distance.

[BM25 keyword search] BM25 is a classic ranking function for keyword search. It scores documents by how often the query terms appear, adjusted for document length, so exact terms such as product codes and error messages match even when no synonym is involved.

[Dense vectors and embeddings] A dense vector is a list of floating point numbers that represents the meaning of a piece of text. An embedding model such as all-MiniLM-L6-v2 turns each document into a 384-dimensional vector, and similar meanings land close together in that space.

Question: How do I combine keyword search and vector search in one query?
Answer:

That prompt is the entire contract between retrieval and generation. Send it to any chat model — this is the only step that needs an API key, and the retrieval half does not care which model answers:

from openai import OpenAI

client = OpenAI()  # needs OPENAI_API_KEY
answer = client.chat.completions.create(
    model="gpt-6.2-sol",
    messages=[{"role": "user", "content": prompt}],
)
print(answer.choices[0].message.content)

Swap in any model you like, including a local one served through an OpenAI-compatible endpoint — the blog's Ollama tutorial covers that setup. When you are done, close the client so the database lock is released: client.close().

Step 10: Moving to production#

Lite is for local workloads, and the docs are explicit about its limits: one process owns a database directory, writes to a collection must be serialized, and there is no authentication, roles, or TLS, no binary, float16, bfloat16, or int8 vector fields, and no product-quantization indexes. When any of those stops being acceptable, you do not rewrite the pipeline — you change the connection. The same MilvusClient code works against Milvus Standalone, Distributed, or Zilliz Cloud by passing a server URI and token instead of a .db path:

client = MilvusClient(uri="http://localhost:19530", token="root:Milvus")

To carry your data with you, export the collection with the documented dump tool (install the bulk-writer extra first, and close the client so the lock is released):

python -m pip install "pymilvus[bulk_writer]==3.0.3"
milvus-lite dump -d ./milvus_rag.db -c docs -p ./data_dir

The dump writes Milvus BulkWriter JSON files you can import into a self-hosted deployment or Zilliz Cloud. And before you scale anything, measure: build a small set of questions with known-good documents, compute recall at k for dense-only, BM25-only, and hybrid, and let the numbers pick the strategy. The published evidence points the same way — in Microsoft's Azure AI Search tests, summarized on Milvus's hybrid search page, hybrid search beat keyword-only and vector-only retrieval on customer data (NDCG@3 of 48.4 versus 40.6 and 43.8), and Anthropic reported that combining contextual embeddings with contextual BM25 cut its top-20 retrieval failure rate from 5.7% to 2.9%. Hybrid is the default for a reason, but your query mix is the final judge.

Which approach should you use?#

SituationBest method
Queries are paraphrases, synonyms, "meaning" questionsDense-only search
Queries contain exact codes, names, or error stringsBM25-only search
Mixed real-world traffic, unknown splitHybrid search with RRF (the default)
One path should dominate (e.g. catalog SKUs)Hybrid search with a weighted ranker
Multi-tenant or per-user documentsHybrid search with a per-request expr filter
100k+ documents, concurrent writers, authMilvus Standalone, Distributed, or Zilliz Cloud

The takeaway#

A RAG pipeline does not need infrastructure to be real. Milvus Lite gives you a genuine vector database — dense search, built-in BM25, hybrid fusion, metadata filters — as a Python library call, and the whole pipeline runs on a laptop in about ten seconds with no server, GPU, or API key. Start with hybrid search and RRF as the default, add per-request filters when your documents gain owners, measure recall on your own questions before tuning anything, and when the corpus outgrows the laptop, change the connection string — not the code.