Milvus Tutorial for RAG

Use Milvus Lite and the MilvusClient API to create collections, insert vectors and search with filters.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 6 · Lesson 5 of 13 · Intermediate

Milvus Tutorial for RAG

Use Milvus Lite and the MilvusClient API to create collections, insert vectors and search with filters.

Milvus is an open-source vector database built for very large collections, from millions to billions of vectors. It comes in several forms that share one API: Milvus Lite, a library that stores data in a local file (ideal for learning and prototypes), standalone and distributed Milvus servers, and the managed Zilliz Cloud. This lesson uses Milvus Lite and the MilvusClient API to build a RAG retriever with metadata filters. The same code runs against a server by changing one line.

What you will learn

  • How to start Milvus Lite and create a collection
  • How to insert chunks with vectors and metadata
  • How to search with filters and return metadata fields
  • How to delete data and move from Lite to a Milvus server

Prerequisites

Version note

Written for pymilvus 3.x with Milvus Lite (November 2026). Milvus Lite runs on Linux and macOS; on Windows use WSL or a Milvus server in Docker. The code has not been executed for this tutorial; check the Milvus documentation if a call differs in your version.

Installation

pip install -U pymilvus milvus-lite sentence-transformers anthropic python-dotenv

Step 1: Create a collection

milvus_rag.py
from pymilvus import MilvusClient
from rag_helpers import ask, embed

client = MilvusClient("milvus_rag.db")      # Milvus Lite: data is stored in this local file
COLLECTION = "policy_chunks"

if client.has_collection(COLLECTION):
    client.drop_collection(COLLECTION)
client.create_collection(collection_name=COLLECTION, dimension=384)   # bge-small-en-v1.5 has 384 dims

This quick-setup form creates a collection with an id primary key, a vector field of the given dimension and cosine similarity, and allows extra fields such as text and metadata to be stored with each entity. For production you can define an explicit schema with typed fields and choose the index type.

Step 2: Insert chunks

CHUNKS = [
    ("Employees get 18 days of paid leave in their first year.", "leave-policy.md", "hr"),
    ("Up to 5 unused leave days can be carried over to next year.", "leave-policy.md", "hr"),
    ("Expense claims must be submitted within 30 days of purchase.", "expenses.md", "finance"),
    ("Laptops are replaced every three years by the IT team.", "it-equipment.md", "it"),
]
vectors = embed([text for text, _, _ in CHUNKS])
data = [{"id": i, "vector": vectors[i].tolist(), "text": text, "source": source, "department": dept}
        for i, (text, source, dept) in enumerate(CHUNKS)]
result = client.insert(collection_name=COLLECTION, data=data)
print(result)
{'insert_count': 4, 'ids': [0, 1, 2, 3]}

Step 3: Search, with and without filters

def search(question: str, k: int = 3, department: str | None = None) -> list[dict]:
    query_vector = embed(question, query=True)[0].tolist()
    results = client.search(
        collection_name=COLLECTION,
        data=[query_vector],                                  # one list of hits per query vector
        limit=k,
        filter=f'department == "{department}"' if department else "",
        output_fields=["text", "source", "department"],
    )
    return results[0]

for hit in search("How much holiday do new employees get?"):
    print(f"{hit['distance']:.3f}  {hit['entity']['text']}")

print(search("What is the deadline?", department="finance")[0]["entity"]["text"])
0.812  Employees get 18 days of paid leave in their first year.
0.655  Up to 5 unused leave days can be carried over to next year.
0.371  Expense claims must be submitted within 30 days of purchase.
Expense claims must be submitted within 30 days of purchase.

With cosine similarity, Milvus reports the similarity in distance, so higher is closer here (unlike some other databases). Filters use Milvus's boolean expression syntax, for example department == "hr" and year >= 2025 or department in ["hr", "it"].

Never build filters from raw user input

The filter is an expression string. Only insert values that come from your own code or an allow-list (such as the user's authenticated department), never free text typed by a user. Recent pymilvus versions also support filter templating with parameters; check the documentation for your version.

Step 4: Answer with RAG

def milvus_rag(question: str) -> str:
    hits = search(question, k=4)
    sources = "\n".join(f'<source id="{i}" file="{h["entity"]["source"]}">{h["entity"]["text"]}</source>'
                        for i, h in enumerate(hits, start=1))
    return ask(f"Answer from the sources only and cite them like [1].\n\n{sources}\n\nQuestion: {question}")

print(milvus_rag("Can I carry unused leave over?"))

Step 5: Update and delete

client.delete(collection_name=COLLECTION, filter='source == "it-equipment.md"')   # re-index a document
client.delete(collection_name=COLLECTION, ids=[0])                                # delete by id

To update a document, delete its old chunks by source and insert the new ones, as described in CRUD and Re-indexing. Milvus also offers upsert for replacing entities by primary key.

Moving to a Milvus server

When you outgrow Milvus Lite, run Milvus standalone (Docker) or distributed (Kubernetes), or use Zilliz Cloud. Only the client constructor changes:

import os
client = MilvusClient(uri=os.environ["MILVUS_URI"], token=os.environ.get("MILVUS_TOKEN", ""))
DeploymentGood for
Milvus LiteLearning, notebooks, tests, small prototypes
Milvus StandaloneSingle-server production up to large collections
Milvus DistributedVery large scale and high query rates on Kubernetes
Zilliz CloudManaged Milvus without operating it yourself

Common errors and troubleshooting

  • Milvus Lite will not install or start on Windows: use WSL, or run a Milvus server in Docker.
  • Dimension mismatch on insert: the vectors must match the collection's dimension.
  • Filter syntax errors: string values need quotes inside the expression; field names must exist.
  • Fields missing from results: list them in output_fields.

Key takeaways

  • Milvus scales from a local file (Milvus Lite) to distributed clusters with the same MilvusClient API.
  • create_collection, insert, search and delete cover most RAG needs.
  • Search accepts boolean filter expressions and returns the requested output_fields.
  • Never build filter expressions from raw user input.

Frequently asked questions

Does Milvus support hybrid search?

Yes. Milvus supports sparse vectors and full-text (BM25) search alongside dense vectors, and can combine several searches with rerankers such as RRF. These use an explicit schema; see the Milvus documentation on hybrid search.

Milvus or Weaviate?

Both are capable open-source databases. Milvus is often chosen for very large scale; Weaviate for its built-in hybrid search and module ecosystem. Benchmark on your own data, as described in Choosing a Vector Database.

Practice exercises

  1. Index 1,000 chunks from your own documents and measure search latency in Milvus Lite.
  2. Add a year field and search only documents from 2025 onwards.

Related tutorials