HNSW, Distance Metrics, Reranking, RAG and Multi-Tenancy

Article · 7:00

How HNSW works and what its parameters do, reranker modules, generative search, and multi-tenancy with tenant lifecycle states.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

HNSW is a navigable small-world graph in layers, and understanding it roughly is what makes its parameters make sense rather than being magic numbers.

Each vector is a node. The graph has layers: the top layer is sparse with long-range links, each lower layer is denser, and the bottom layer contains everything. A search enters at the top, greedily walks toward the query vector, drops a layer, walks again, and so on - so it reaches the right region in a few long hops and then refines locally. That is why it is fast, and why it is approximate: a greedy walk can enter the wrong region and never recover.

The three parameters, and what each costs:

  • ef (search time) - how many candidates the search keeps in its dynamic list. Higher means it explores more, finds better neighbours, and takes longer. This is the recall dial and it can be changed at any time, including per query in some paths. Too low is the single commonest cause of unexplained poor recall in a self-managed Weaviate.
  • efConstruction (build time) - the same idea while building the graph. Higher makes a better-connected graph, so searches are more accurate for a given ef, and the import is slower. Changing it does not improve the existing graph - the links are already built.
  • maxConnections - links per node per layer. Higher means better recall and more memory. Changing it requires rebuilding the index.

The practical sequence: set efConstruction and maxConnections before the import, because changing them means a rebuild; then tune ef afterwards, because it is free to change and it is where most of the recall is. Weaviate also supports dynamic ef - a range with a multiplier applied to the query's limit - which is usually better than a fixed value because the right ef depends on how many results you asked for.

Reranker modules bring the Pinecone course's cross-encoder inside the database: enable a reranker module and add a rerank clause to a query, and Weaviate retrieves candidates and reranks them server-side. The same trade applies - a large precision gain for tens to hundreds of milliseconds - and doing it in the database removes a network round trip and a service from your architecture.

Generative search goes further: a generative module takes the retrieved objects, puts them in a prompt and returns a generated answer, in the same query. single_prompt runs per object; grouped_task runs once over all of them. It is genuinely convenient for a prototype. The honest caution: it puts your prompt in your database query, which makes prompt changes a database concern, and it gives you less control over context assembly, deduplication and the relevance threshold than the Pinecone course argued you need. Use it to prototype; move the generation into your application when the retrieval-side concerns start to matter.

Multi-tenancy is first-class here, and better than a namespace. Enabling it on a collection makes every object belong to a tenant, every query require a tenant, and - crucially - each tenant gets its own shard and its own vector index. The consequences are substantial: tenant data is physically separated; a tenant can be deleted cheaply; a small tenant's index is small, so searches within it are fast; and tenants have lifecycle states. ACTIVE is normal; INACTIVE keeps the tenant on disk but unloads it from memory; OFFLOADED moves it to cloud storage entirely. That lets you host very many mostly-idle tenants on modest hardware, which is a genuine architectural capability rather than a convenience - and it is the strongest argument for Weaviate over a namespace-based design.

Laboratory exercise 3 - a service with tenants, measured.

Build a product search service with multi-tenancy enabled and run at least 100 concurrent clients across several tenants.

Demonstrate the ef effect: measure recall@5 and p95 latency at ef of 16, 32, 64, 128, 256 and 512 on the same collection. Produce the curve. This is the module's main artefact and it shows the approximate-search trade-off directly.

Demonstrate that efConstruction is build-time: build two collections with efConstruction of 64 and 256, measure recall at the same ef, then change the 64 collection's efConstruction to 256 and show recall unchanged.

Implement dynamic ef and compare it with the best fixed value across several limit values.

Add a reranker module and measure the recall and latency change, then compare it with an application-side cross-encoder doing the same job.

Implement generative search both ways: with a grouped_task in the database, and with retrieval in the database and generation in your application with a relevance threshold and deduplication. Demonstrate the threshold declining an unanswerable question in your version and show what the in-database version does with the same question.

Then demonstrate the tenant lifecycle: create 200 tenants, measure memory with all ACTIVE, then set most to INACTIVE and measure again. Record the memory saved and the latency of the first query to a reactivated tenant.

Deliverable: the service, the ef recall and latency curve, the efConstruction immutability demonstration, the dynamic ef comparison, the reranker measurements both ways, both generative implementations with the threshold demonstration, and the tenant lifecycle memory and latency measurements.

PY Example 1 202 lines
# ==================================================================
# *** HNSW, roughly - which is what makes the parameters make sense. ***
# ==================================================================
# Each vector is a NODE. The graph has LAYERS:
#   top layer     SPARSE, with LONG-RANGE links
#   lower layers  DENSER
#   bottom layer  EVERYTHING
#
# A search ENTERS AT THE TOP, greedily walks toward the query vector,
# DROPS A LAYER, walks again, and so on - so it reaches the right
# region in a few LONG HOPS and then refines LOCALLY.
#
# *** THAT IS WHY IT IS FAST, AND WHY IT IS APPROXIMATE: A GREEDY
# *** WALK CAN ENTER THE WRONG REGION AND NEVER RECOVER. ***

# ------------------------------------------------------------------
# THE THREE PARAMETERS, and what each costs.
# ------------------------------------------------------------------
client.collections.create(
    name="ProductTuned",
    vector_index_config=wvc.config.Configure.VectorIndex.hnsw(
        distance_metric=wvc.config.VectorDistances.COSINE,

        # ef - SEARCH TIME. How many candidates the search keeps.
        # *** THE RECALL DIAL, AND IT CAN BE CHANGED AT ANY TIME. ***
        # Too low is THE COMMONEST CAUSE OF UNEXPLAINED POOR RECALL
        # in a self-managed Weaviate.
        ef=64,

        # ef_construction - BUILD TIME. The same idea while BUILDING.
        # Higher = a better-connected graph, so searches are more
        # accurate FOR A GIVEN ef, and the IMPORT IS SLOWER.
        # *** CHANGING IT DOES NOT IMPROVE THE EXISTING GRAPH. ***
        ef_construction=128,

        # max_connections - links per node per layer. Higher = better
        # recall and MORE MEMORY.
        # *** CHANGING IT REQUIRES REBUILDING THE INDEX. ***
        max_connections=32,
    ),
)

# *** THE PRACTICAL SEQUENCE: ***
#   1. set ef_construction and max_connections BEFORE THE IMPORT,
#      because changing them means a REBUILD
#   2. tune ef AFTERWARDS, because it is FREE to change and it is
#      WHERE MOST OF THE RECALL IS

# ------------------------------------------------------------------
# *** THE ef CURVE. The module's main artefact. ***
# ------------------------------------------------------------------
for ef in [16, 32, 64, 128, 256, 512]:
    products.config.update(
        vector_index_config=wvc.config.Reconfigure.VectorIndex.hnsw(ef=ef))
    print(ef, evaluate_recall_and_latency(products, GROUND_TRUTH))
#
#   ef    recall@5   p50     p95
#   16      0.68     2.1ms   4.0ms
#   32      0.79     2.8ms   5.4ms
#   64      0.87     4.1ms   8.2ms
#  128      0.93     7.0ms  14.1ms
#  256      0.96    12.8ms  26.3ms
#  512      0.97    24.1ms  49.7ms
#
# *** THE APPROXIMATE-SEARCH TRADE-OFF, DIRECTLY. *** And note the
# shape: recall rises steeply and then flattens while latency keeps
# growing linearly. The useful operating point is at the knee, and
# you cannot find the knee without the ground truth.

# DYNAMIC ef - usually better than a fixed value, because the right
# ef depends on HOW MANY RESULTS YOU ASKED FOR:
products.config.update(
    vector_index_config=wvc.config.Reconfigure.VectorIndex.hnsw(
        dynamic_ef_min=100, dynamic_ef_max=500, dynamic_ef_factor=8))
#   ef = limit * factor, clamped to [min, max]. A limit of 10 gets
#   ef 100; a limit of 50 gets 400. Compare it with the best fixed
#   value across several limits.

# *** DEMONSTRATE THAT ef_construction IS BUILD-TIME: ***
#   build A with ef_construction=64, B with 256, import the same data
#     A at ef=128: recall@5 0.89     B at ef=128: recall@5 0.94
#   now set A's ef_construction to 256 and re-measure
#     A at ef=128: recall@5 0.89     <- UNCHANGED. The links are
#                                       already built.
#   Only a REIMPORT (or a rebuild) changes it.

# ==================================================================
# RERANKER MODULES: the Pinecone cross-encoder, inside the database.
# ==================================================================
#   ENABLE_MODULES: '...,reranker-transformers'
r = products.query.hybrid(
    query="a quiet keyboard for an open-plan office",
    alpha=0.6, limit=50,
    rerank=wvc.query.Rerank(prop="description",
                            query="quiet keyboard open plan office"),
    return_metadata=wvc.query.MetadataQuery(score=True),
)
final = r.objects[:5]
#   The SAME trade as the Pinecone course - a large precision gain
#   for tens to hundreds of ms - and doing it IN THE DATABASE removes
#   A NETWORK ROUND TRIP AND A SERVICE from your architecture.
#
#   Measure both ways:
#     in-database reranker       recall@5 0.96   p95 174 ms
#     application cross-encoder  recall@5 0.96   p95 203 ms
#   Same quality; the difference is the round trip and one fewer
#   thing to deploy - against less control over the model version.

# ==================================================================
# GENERATIVE SEARCH: convenient, and read the caution.
# ==================================================================
#   ENABLE_MODULES: '...,generative-openai'  (or -ollama, -cohere...)
r = products.generate.hybrid(
    query="a quiet keyboard for an open-plan office",
    alpha=0.6, limit=5,
    grouped_task="Recommend one of these products and say why. "
                 "Cite the SKU.",
    grouped_properties=["title", "description", "sku", "price"],
)
print(r.generated)
#   single_prompt=... runs PER OBJECT; grouped_task runs ONCE over
#   all of them.

# *** THE HONEST CAUTION: ***
#   * it puts YOUR PROMPT IN YOUR DATABASE QUERY, which makes prompt
#     changes a DATABASE concern - and prompts change far more often
#     than schemas
#   * LESS CONTROL over context assembly, DEDUPLICATION and the
#     RELEVANCE THRESHOLD than the Pinecone course argued you need
#
# *** USE IT TO PROTOTYPE; MOVE THE GENERATION INTO YOUR APPLICATION
# *** WHEN THE RETRIEVAL-SIDE CONCERNS START TO MATTER. *** And
# demonstrate the difference: ask something your catalogue cannot
# answer. Your version declines; the in-database version generates
# an answer from the five nearest products, confidently.

# ==================================================================
# *** MULTI-TENANCY: FIRST-CLASS, AND BETTER THAN A NAMESPACE. ***
# ==================================================================
tenanted = client.collections.create(
    name="TenantProduct",
    multi_tenancy_config=wvc.config.Configure.multi_tenancy(
        enabled=True,
        auto_tenant_creation=True,      # create on first write
        auto_tenant_activation=True,    # reactivate on access
    ),
    vectorizer_config=wvc.config.Configure.Vectorizer.text2vec_transformers(),
    # DYNAMIC index, because most tenants are SMALL:
    vector_index_config=wvc.config.Configure.VectorIndex.dynamic(
        threshold=10000,
        hnsw=wvc.config.Configure.VectorIndex.hnsw(ef=64),
        flat=wvc.config.Configure.VectorIndex.flat()),
    properties=[...],
)

tenanted.tenants.create([
    wvc.tenants.Tenant(name="acme"),
    wvc.tenants.Tenant(name="globex"),
])

acme = tenanted.with_tenant("acme")
acme.data.insert(properties={...}, uuid=generate_uuid5("KB-4471-B"))
r = acme.query.near_text(query="quiet keyboard", limit=10)
#   *** EVERY QUERY REQUIRES A TENANT. *** Omitting it is an ERROR,
#   not a cross-tenant read - which is a materially stronger
#   guarantee than the Pinecone namespace design, where forgetting
#   the namespace reads the wrong data silently.

# *** EACH TENANT GETS ITS OWN SHARD AND ITS OWN VECTOR INDEX. ***
# The consequences are substantial:
#   * tenant data is PHYSICALLY SEPARATED
#   * a tenant can be DELETED CHEAPLY (drop the shard)
#   * a SMALL TENANT'S INDEX IS SMALL, so searches within it are
#     FAST - the opposite of a shared index where every tenant pays
#     for the total size
#   * and TENANTS HAVE LIFECYCLE STATES:

tenanted.tenants.update([
    wvc.tenants.Tenant(name="globex",
                       activity_status=wvc.tenants.TenantActivityStatus.INACTIVE)
])
#   ACTIVE     normal: in memory, queryable
#   INACTIVE   ON DISK, UNLOADED FROM MEMORY. Queries must reactivate
#              it (automatic with auto_tenant_activation, at a
#              first-query latency cost).
#   OFFLOADED  moved to CLOUD STORAGE entirely. Cheapest, slowest to
#              return.
#
# *** THAT LETS YOU HOST VERY MANY MOSTLY-IDLE TENANTS ON MODEST
# *** HARDWARE, WHICH IS A GENUINE ARCHITECTURAL CAPABILITY RATHER
# *** THAN A CONVENIENCE - and it is the strongest argument for
# *** Weaviate over a namespace-based design. ***
#
# MEASURE IT: 200 tenants, all ACTIVE, then most INACTIVE.
#   200 ACTIVE                 resident memory  ___ GB
#   10 ACTIVE / 190 INACTIVE   resident memory  ___ GB
#   first query to a reactivated tenant         ___ ms
# Those three numbers decide whether this architecture works for
# your tenant count, and they are the deliverable.

for t in tenanted.tenants.get().values():
    print(t.name, t.activity_status)

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.