Apply Now Apply Now Apply Now
header_logo
Post thumbnail
ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Milvus Tutorial: Open-Source Vector Database Guide

By HCL GUVI

Milvus is an open-source vector database designed for large-scale similarity search over embeddings.
It supports local development with Milvus Lite and production deployments with standalone or distributed clusters.
This tutorial shows how to set up Milvus, create a collection, insert vectors, and run your first vector search in Python.

Table of contents


  1. TL;DR Summary
    • Direct Answer
  2. What Is Milvus?
  3. Why Use Milvus?
  4. Core Concepts: Collections, Schema, and Indexes
    • Collections
    • Schema
    • Indexes
  5. Step-by-Step: Setting Up Milvus
    • Step 1: Install the Python Client
    • Step 2: Create a Local Milvus Database
    • Step 3: Define a Collection Schema
    • Step 4: Prepare Sample Data
    • Step 5: Generate Embeddings
    • Step 6: Insert Data into Milvus
  6. Querying for Similar Vectors
    • Step 7: Embed a Query
    • Step 8: Run a Vector Search Query
  7. Filtering by Scalar Fields
  8. Building a Simple RAG Example
  9. Deployment Options: Lite, Standalone, and Distributed
    • Milvus Lite
    • Milvus Standalone
    • Milvus Distributed
  10. Common Mistakes to Avoid
  11. Conclusion
  12. FAQs
    • What is Milvus used for?
    • Do I need to generate embeddings myself?
    • How do I choose the collection dimension?
    • What metric type should I use?

TL;DR Summary

  • Milvus is an open-source vector database for similarity search.
  • You store embeddings in collections with defined schemas and indexes.
  • Queries return the most similar vectors based on distance metrics.
  • Milvus Lite is ideal for local development; clusters are for production.
  • Common use cases include semantic search, recommendations, and RAG.

Direct Answer

Milvus Vector Database stores high-dimensional vector embeddings and provides fast approximate nearest-neighbor search. You define a collection schema, insert vectors with optional metadata, build an index, and then query the collection with a new embedding to find the most similar items. Milvus can run locally as Milvus Lite or as a scalable cluster, making it suitable for prototypes and production AI applications such as semantic search, recommendations, and RAG.

What Is Milvus?

Milvus is an open-source vector database built for managing, indexing, and searching large collections of vector embeddings. It is designed for AI workloads that require fast, scalable similarity search over high-dimensional data.

Key characteristics:

  • Open-source with a large community and ecosystem.
  • Supports local (Milvus Lite), standalone, and distributed deployments.
  • Optimized for low-latency approximate nearest-neighbor search.
  • Supports metadata filtering, hybrid search, and multi-vector fields.
  • Integrates with popular embedding models and frameworks.

Milvus is commonly used for:

  • Semantic search over documents, products, or knowledge bases.
  • Recommendation systems.
  • Retrieval-Augmented Generation (RAG) for LLMs.
  • Image, audio, and multimodal search.
  • Clustering, deduplication, and anomaly detection.

Why Use Milvus?

Milvus offers:

  • Flexible deployment options from local file-based databases to cloud-native clusters.
  • Rich indexing strategies for different performance and accuracy trade-offs.
  • Support for scalar fields alongside vector fields for filtering and joins.
  • Horizontal scalability for large datasets and high query throughput.
  • A Python SDK and integrations with LangChain, LlamaIndex, and other tools.

This makes Milvus suitable for both experimentation and production-grade AI systems.

Milvus is an open-source vector database you can run locally or on Kubernetes, letting you store embeddings, build indexes, and run fast similarity and hybrid searches for RAG and other GenAI. Learn AI & ML with HCL GUVI’s Artificial Intelligence and Machine Learning course. 

Core Concepts: Collections, Schema, and Indexes

Core Concepts: Collections, Schema, and Indexes

Before using Milvus, you need to understand three core ideas.

1. Collections

A collection in Milvus is similar to a table in a relational database.

  • It holds entities (rows) with vector and scalar fields.
  • Each collection has a defined schema.
  • You can have multiple collections for different datasets or use cases.

2. Schema

A schema defines the fields in a collection.

  • Vector fields store embeddings (for example, float vectors of dimension 768).
  • Scalar fields store metadata (for example, IDs, text, categories, timestamps).
  • You specify which field is the primary key and which fields are indexed.

3. Indexes

An index in Milvus accelerates vector search.

  • You choose an index type (for example, HNSW, IVF_FLAT, SCANN).
  • You configure parameters such as M, efConstruction, or nlist.
  • Milvus builds the index over the vector field to enable fast approximate nearest-neighbor search.

Without an index, search over large datasets can be slow.

Step-by-Step: Setting Up Milvus

This section walks you through a minimal end-to-end setup using Python and Milvus Lite.

Step 1: Install the Python Client

Install the pymilvus package, which includes the Python client and Milvus Lite.

bash

pip install -U pymilvus

Optionally, install the model utilities for built-in embeddings:

bash

pip install "pymilvus[model]"

Milvus Lite requires:

  • Python 3.8 or higher.
  • A supported OS (Linux, macOS, or Windows with WSL).

Step 2: Create a Local Milvus Database

Milvus Lite stores data in a local file. You can instantiate a client by specifying a file path.

python

from pymilvus import MilvusClient

client = MilvusClient("milvus_demo.db")

This creates or opens a local vector database in milvus_demo.db.

Step 3: Define a Collection Schema

Define a collection with a vector field and optional scalar fields.

python

collection_name = "demo_collection"

# Drop collection if it exists (for tutorial purposes)

if client.has_collection(collection_name):

    client.drop_collection(collection_name)

client.create_collection(

    collection_name=collection_name,

    dimension=768,           # Match your embedding dimension

    metric_type="COSINE",    # or "L2", "IP"

    auto_id=False            # We will provide our own IDs

)

Adjust:

  • dimension to match your embedding model (for example, 768, 1536).
  • metric_type based on your model’s recommended distance.
  • auto_id depending on whether you want Milvus to generate IDs.

Step 4: Prepare Sample Data

Suppose you have a few documents:

python

documents = [

    {

        "id": 1,

        "text": "Milvus is an open-source vector database for similarity search.",

    },

    {

        "id": 2,

        "text": "Vector search enables semantic search over embeddings.",

    },

    {

        "id": 3,

        "text": "RAG systems use vector databases to retrieve relevant context.",

    },

]

Each document has:

  • A unique id.
  • A text field to embed.
  • Optionally, additional metadata fields.

Step 5: Generate Embeddings

Use an embedding model to convert text into vectors. With pymilvus[model], you can use the default embedding function:

python

from pymilvus import model

embedding_fn = model.DefaultEmbeddingFunction()

texts = [doc["text"] for doc in documents]

vectors = embedding_fn.encode_documents(texts)

vectors will be a list of vectors (lists of floats) matching the specified dimension.

Step 6: Insert Data into Milvus

Combine IDs, vectors, and metadata, then insert:

python

entities = [

    {

        "id": doc["id"],

        "vector": vec,

        "text": doc["text"],

        # Add more metadata if needed

    }

    for doc, vec in zip(documents, vectors)

]

client.insert(

    collection_name=collection_name,

    data=entities

)

Milvus stores and indexes these entities in the collection.

Querying for Similar Vectors

Now you can perform vector search.

Step 7: Embed a Query

Embed your query text using the same embedding function:

GUVI Ad

python

query_text = "How does vector search work?"

query_vectors = embedding_fn.encode_queries([query_text])

Using the same embedding model is critical for meaningful similarity.

Step 8: Run a Vector Search Query

Query the collection for the top-k most similar vectors:

python

results = client.search(

    collection_name=collection_name,

    data=query_vectors,

    limit=2,

    output_fields=["id", "text"]

)

for hits in results:

    for hit in hits:

        print("ID:", hit["id"])

        print("Score:", hit["score"])

        print("Text:", hit["text"])

        print("-" * 40)

Milvus returns:

  • id: the document ID.
  • score: similarity score (higher is more similar for cosine/IP).
  • text and other requested fields.

This is the core of semantic search: you search by meaning, not by exact keywords.

Filtering by Scalar Fields

Milvus supports filtering by scalar fields during search.

For example, filter by an ID range or category:

python

results = client.search(

    collection_name=collection_name,

    data=query_vectors,

    limit=2,

    filter="id >= 2",

    output_fields=["id", "text"]

)

Common filter expressions include:

  • “id == 1” – exact match.
  • “id in [1, 2, 3]” – in a list.
  • “category == ‘tutorials'” – string equality.
  • “timestamp > 1700000000” – time-based filtering.
  • Logical combinations using and, or, not.

Metadata filtering is useful for:

  • Restricting search to certain users, tenants, or domains.
  • Limiting by date, language, or content type.
  • Implementing access control alongside semantic search.

Milvus is an open-source vector database you can run locally or on Kubernetes, letting you store embeddings, build indexes, and run fast similarity and hybrid searches for RAG and other GenAI. Learn AI & ML with HCL GUVI’s Artificial Intelligence and Machine Learning course. 

Building a Simple RAG Example

Milvus is often used in Retrieval-Augmented Generation (RAG) pipelines.

A minimal RAG flow:

  1. User asks a question.
  2. Embed the question.
  3. Query Milvus for top-k relevant documents.
  4. Pass the retrieved text plus the question to an LLM.
  5. LLM generates an answer grounded in the retrieved context.

Conceptual code:

python

# 1. User question

question = "What is Milvus used for?"

# 2. Embed question

query_vectors = embedding_fn.encode_queries([question])

# 3. Retrieve context

results = client.search(

    collection_name=collection_name,

    data=query_vectors,

    limit=3,

    output_fields=["id", "text"]

)

contexts = [hit["text"] for hits in results for hit in hits]

context_text = "\n\n".join(contexts)

# 4. Build prompt for LLM (pseudo-code)

prompt = f"""

Context:

{context_text}

Question: {question}

Answer based on the context above:

"""

# 5. Send prompt to your LLM API and return the response

This pattern powers many AI assistants, document Q&A systems, and knowledge-base chatbots.

GUVI Ad

Deployment Options: Lite, Standalone, and Distributed

Milvus offers several deployment modes.

Milvus Lite

  • Runs locally using a file-based database.
  • Ideal for prototyping, tutorials, and small projects.
  • No Docker or cluster management required.
  • Limited scale compared to full clusters.

Use Milvus Lite when you want to experiment quickly on a single machine.

Milvus Standalone

  • Runs as a single-node server in Docker or Kubernetes.
  • Suitable for small to medium production workloads.
  • Supports indexes, multiple collections, and concurrent queries.
  • Easier to operate than a full distributed cluster.

Use Standalone for pilot projects and moderate-scale deployments.

Milvus Distributed

  • Runs as a multi-node cluster with separate components (coordinators, query nodes, data nodes, index nodes).
  • Designed for large-scale, high-throughput production systems.
  • Supports horizontal scaling, high availability, and fault tolerance.
  • Requires more operational expertise and infrastructure.

Use Distributed for enterprise-scale AI applications with large datasets and strict SLAs.

Common Mistakes to Avoid

  • Using different embedding models for indexing and querying.
  • Choosing a collection dimension that does not match your vectors.
  • Not defining a primary key or unique ID field.
  • Ignoring scalar fields and losing the ability to filter or trace results.
  • Using an inappropriate metric type for your embedding model.
  • Expecting exact keyword matching instead of semantic similarity.
  • Not building an index before running large-scale searches.
  • Treating Milvus as a general-purpose database instead of a vector index.
  • Skipping evaluation of retrieval quality in RAG applications.
  • Overlooking resource requirements for distributed deployments.
💡 Did You Know?

Milvus can handle billions of vectors across a distributed cluster while maintaining low-latency search. You can combine vector similarity with scalar filters to build multi-tenant, domain-specific, or access-controlled search systems.

Conclusion

Milvus Vector Database provides a flexible, open-source platform for building semantic search, recommendations, and RAG applications. By storing embeddings in collections with defined schemas and indexes, you can retrieve the most similar items based on meaning rather than keywords.

With a few lines of Python, you can run Milvus locally, insert vectors, and perform similarity queries. As your application grows, you can scale to standalone or distributed deployments, add advanced indexing, and integrate with LLMs to build powerful AI-driven experiences.

FAQs

What is Milvus used for?

Milvus is used for vector similarity search, semantic search, recommendations, duplicate detection, and retrieval for RAG applications.

Do I need to generate embeddings myself?

Yes. You generate embeddings using an embedding model and store the resulting vectors in Milvus. Milvus focuses on storage, indexing, and search rather than embedding generation.

How do I choose the collection dimension?

The collection dimension must match the output dimension of your embedding model (for example, 768, 1536). Check your model’s documentation.

What metric type should I use?

Use the metric type recommended by your embedding model (often COSINE or IP). The metric must be consistent between indexing and querying.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR Summary
    • Direct Answer
  2. What Is Milvus?
  3. Why Use Milvus?
  4. Core Concepts: Collections, Schema, and Indexes
    • Collections
    • Schema
    • Indexes
  5. Step-by-Step: Setting Up Milvus
    • Step 1: Install the Python Client
    • Step 2: Create a Local Milvus Database
    • Step 3: Define a Collection Schema
    • Step 4: Prepare Sample Data
    • Step 5: Generate Embeddings
    • Step 6: Insert Data into Milvus
  6. Querying for Similar Vectors
    • Step 7: Embed a Query
    • Step 8: Run a Vector Search Query
  7. Filtering by Scalar Fields
  8. Building a Simple RAG Example
  9. Deployment Options: Lite, Standalone, and Distributed
    • Milvus Lite
    • Milvus Standalone
    • Milvus Distributed
  10. Common Mistakes to Avoid
  11. Conclusion
  12. FAQs
    • What is Milvus used for?
    • Do I need to generate embeddings myself?
    • How do I choose the collection dimension?
    • What metric type should I use?