Weaviate Tutorial for RAG

Run Weaviate, create a collection, import objects and use vector, keyword and hybrid queries.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 6 · Lesson 4 of 13 · Intermediate

Weaviate Tutorial for RAG

Run Weaviate, create a collection, import objects and use vector, keyword and hybrid queries.

Weaviate is an open-source vector database. Out of the box it offers vector search, BM25 keyword search and hybrid search, plus filtering and multi-tenancy. You can run it locally with Docker, self-host it, or use Weaviate Cloud. In this lesson you run Weaviate locally, create a collection that stores your own embeddings, import chunks, and run vector, keyword, hybrid and filtered queries for RAG.

What you will learn

  • How to run Weaviate with Docker and connect with the Python client v4
  • How to create a collection for self-provided vectors and import chunks
  • How to run vector, BM25, hybrid and filtered searches
  • How to plug Weaviate retrieval into a RAG answer

Prerequisites

Version note

Written against the Weaviate documentation of November 2026 (server 1.41, Python client 4.x, which uses the vector_config= API introduced in client 4.16). The code has not been executed against a live server for this tutorial; check the Weaviate documentation if a call differs in your version.

Step 1: Run Weaviate locally

docker run -d --name weaviate -p 8080:8080 -p 50051:50051 \
  -v weaviate_data:/var/lib/weaviate \
  cr.weaviate.io/semitechnologies/weaviate:1.41.0

pip install -U weaviate-client sentence-transformers anthropic python-dotenv

Port 8080 serves the REST API and 50051 serves gRPC, which the Python client uses for fast queries. The volume keeps your data when the container is replaced. This minimal container has no vectorizer module, which suits us: we create embeddings ourselves with the tutorial's local model.

Step 2: Create a collection

weaviate_setup.py
import weaviate
from weaviate.classes.config import Configure, DataType, Property, VectorDistances

with weaviate.connect_to_local() as client:
    if client.collections.exists("PolicyChunk"):
        client.collections.delete("PolicyChunk")
    client.collections.create(
        "PolicyChunk",
        vector_config=Configure.Vectors.self_provided(
            vector_index_config=Configure.VectorIndex.hnsw(distance_metric=VectorDistances.COSINE),
        ),
        properties=[
            Property(name="text", data_type=DataType.TEXT),
            Property(name="source", data_type=DataType.TEXT),
            Property(name="department", data_type=DataType.TEXT),
        ],
    )
    print("created")

self_provided means Weaviate stores the vectors you send instead of creating them. When you bring your own vectors, set the distance metric to match your embedding model (cosine for most text models). Text properties are also indexed for BM25 keyword search automatically.

Step 3: Import chunks with their vectors

weaviate_import.py
import weaviate
from weaviate.classes.data import DataObject
from rag_helpers import embed

CHUNKS = [
    {"text": "Employees get 18 days of paid leave in their first year.", "source": "leave-policy.md", "department": "hr"},
    {"text": "Up to 5 unused leave days can be carried over to next year.", "source": "leave-policy.md", "department": "hr"},
    {"text": "Expense claims must be submitted within 30 days of purchase.", "source": "expenses.md", "department": "finance"},
    {"text": "Laptops are replaced every three years by the IT team.", "source": "it-equipment.md", "department": "it"},
]

with weaviate.connect_to_local() as client:
    collection = client.collections.get("PolicyChunk")
    vectors = embed([c["text"] for c in CHUNKS])
    objects = [DataObject(properties=chunk, vector=vectors[i].tolist()) for i, chunk in enumerate(CHUNKS)]
    collection.data.ingest(objects)
    print(f"sent {len(objects)} objects")

For large imports, use the client's batching (collection.batch), which sends objects in parallel batches; check collection.batch.failed_objects afterwards, because a batch import does not raise an exception for individual failures.

Step 4: Search

weaviate_search.py
import weaviate
from weaviate.classes.query import Filter, MetadataQuery
from rag_helpers import embed

question = "How much holiday do new staff get?"
query_vector = embed(question, query=True)[0].tolist()

with weaviate.connect_to_local() as client:
    chunks = client.collections.get("PolicyChunk")

    print("Vector search:")
    response = chunks.query.near_vector(near_vector=query_vector, limit=2,
                                        return_metadata=MetadataQuery(distance=True))
    for o in response.objects:
        print(f"  {o.metadata.distance:.3f}  {o.properties['text']}")

    print("Keyword (BM25) search:")
    response = chunks.query.bm25(query="expense claims", limit=2, return_metadata=MetadataQuery(score=True))
    for o in response.objects:
        print(f"  {o.metadata.score:.3f}  {o.properties['text']}")

    print("Hybrid search:")
    response = chunks.query.hybrid(query=question, vector=query_vector, alpha=0.5, limit=2,
                                   return_metadata=MetadataQuery(score=True))
    for o in response.objects:
        print(f"  {o.metadata.score:.3f}  {o.properties['text']}")

    print("Filtered vector search (finance only):")
    response = chunks.query.near_vector(near_vector=query_vector, limit=2,
                                        filters=Filter.by_property("department").equal("finance"))
    for o in response.objects:
        print(f"  {o.properties['text']}")
Vector search:
  0.182  Employees get 18 days of paid leave in their first year.
  0.341  Up to 5 unused leave days can be carried over to next year.
Keyword (BM25) search:
  1.247  Expense claims must be submitted within 30 days of purchase.
  ...
Hybrid search:
  0.927  Employees get 18 days of paid leave in their first year.
  ...
Filtered vector search (finance only):
  Expense claims must be submitted within 30 days of purchase.

Distances are cosine distances (lower is closer); hybrid and BM25 scores are higher-is-better. Your exact numbers will differ. In hybrid search, alpha weights the two halves: 1 is pure vector search, 0 is pure keyword search. The query string drives the keyword half, and the vector you pass drives the vector half.

Step 5: Answer with RAG

from rag_helpers import ask

def weaviate_rag(question: str) -> str:
    query_vector = embed(question, query=True)[0].tolist()
    with weaviate.connect_to_local() as client:
        response = client.collections.get("PolicyChunk").query.hybrid(
            query=question, vector=query_vector, alpha=0.5, limit=4)
    sources = "\n".join(f'<source id="{i}" file="{o.properties["source"]}">{o.properties["text"]}</source>'
                        for i, o in enumerate(response.objects, start=1))
    return ask(f"Answer from the sources only and cite them like [1].\n\n{sources}\n\nQuestion: {question}")

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

In a real application, open the client once at start-up and reuse it, rather than connecting for every question.

Common errors and troubleshooting

  • Connection refused or gRPC errors: the container is not running, or port 50051 is not published.
  • Vector length mismatch: every vector in a collection must have the same dimension; re-create the collection if you change the embedding model.
  • TypeError with numpy arrays: convert vectors to plain lists with .tolist().
  • API differences in examples you find online: older examples use the v3 client (weaviate.Client) or vectorizer_config=; the v4 client uses connect_to_local() and collections.

Key takeaways

  • Weaviate supports vector, BM25 and hybrid search in one database.
  • Use Configure.Vectors.self_provided() to store embeddings you create yourself, with a matching distance metric.
  • query.hybrid(query=..., vector=..., alpha=...) combines keyword and vector relevance.
  • Filters (Filter.by_property(...)) narrow results by metadata, which is also how you enforce access rules.

Frequently asked questions

Can Weaviate create the embeddings for me?

Yes. Weaviate has vectorizer integrations for many model providers; you configure one on the collection and it embeds text on import and query. This lesson uses self-provided vectors to keep the embedding model consistent across the tutorial.

Does Weaviate support multi-tenancy?

Yes, with per-tenant shards that isolate each tenant's data; see Metadata Filtering and Multi-Tenancy for the general patterns.

Practice exercises

  1. Run the same five questions with alpha = 0, 0.5 and 1 and compare which chunks come first.
  2. Add a updated date property and filter out documents older than a year.

Related tutorials