DEV Community

Cover image for ScaNN Vector Search and Hybrid RAG on AlloyDB: Tuning Recall, Latency, and Evals

ScaNN Vector Search and Hybrid RAG on AlloyDB: Tuning Recall, Latency, and Evals

Build the AlloyDB vector mental model first (K-means trees, PCA + SQ8/AH quantization, adaptive bitmap filtering, BM25 RRF fusion, and two-layer evals), then replace fragile vector pipelines with a single PostgreSQL engine that scales to 10 billion vectors.

Series: A five-part, hands-on series for engineers moving PostgreSQL and AI workloads from prototype to exit-ready scale on Google Cloud AlloyDB. Part 1 covers Express prototyping, MCP coding workflows, and Cloud Run lazy connection pooling. Part 2 builds production vector search, hybrid RAG, and two-layer evals with ScaNN. Part 3 locks down autonomous database agents with Parameterized Secure Views, Model Armor, and Smart Batching. Part 4 scales HTAP analytics with disaggregated WAL storage, the Columnar Engine, and Zero-ETL Iceberg/BigQuery pipelines. Part 5 hardens networking (PSA vs. PSC), zero-downtime cutovers, and portable exit strategies.

This is Part 2.

The problem: it works on 10,000 rows, then stalls at 10 million

Your RAG prototype worked on the first try. You enabled pgvector, built an HNSW index over 10,000 embedded chunks, ran ORDER BY embedding <=> $1 LIMIT 10, and wired the output into Gemini. Latency was single-digit milliseconds and demo answers looked sharp.

Then production traffic arrived. At 15 million 768- or 3,072-dimensional vectors, the HNSW pointer graph outgrew RAM, write throughput collapsed under pointer rewiring, and filtered queries like WHERE tenant_id = 42 AND price <= 10 started returning 2 rows instead of 10. Worse, semantic search alone kept missing exact SKU codes and error identifiers, and when users reported "the agent says it cannot find information that is right there in the docs," nobody could tell whether the vector index, the reranker, or the LLM prompt caused the miss.

None of these are mysteries once you see how the database executes each stage. Standard pgvector HNSW is an in-memory multi-layer pointer graph with no inline predicate filtering. Pure vector search has no notion of exact lexical term saturation. And single-metric LLM grading mixes retrieval failures with generation failures. AlloyDB solves all three inside PostgreSQL by pairing Google's tree-quantized ScaNN index, Adaptive Filtering, BM25 + RRF hybrid search, sub-100 ms ai.rank() cross-encoder reranking, and SQL-native recall and drift instrumentation.

What you'll be able to do

By the end of this post you should be able to:

  • Identify the exact AlloyDB extensions, versions, IAM roles, and ScaNN/Columnar GUCs required for hybrid RAG (vector 0.8.5.google-1, alloydb_scann 0.1.3, pg_textsearch 1.3, google_ml_integration 1.5.6+ / 1.6.4 latest, scann.satisfy_limit, scann.enable_pca).
  • Explain how ScaNN's 2- to 4-level partitioned K-means tree, PCA compression, SQ8/AH/FLAT quantization, and 50 * K exact re-ranking differ from pgvector HNSW pointer graphs.
  • Configure adaptive filtered vector search (scann.enable_preview_features=on, scann.satisfy_limit = 'relaxed_order', scann.max_num_leaves_to_search_pct) and Columnar Engine index caching (google_columnar_engine_add_index()).
  • Diagnose insufficient recall on selective WHERE predicates, stale/skewed ScaNN partitions via pg_stat_ann_indexes, and agent latency or factuality faults across OpenTelemetry spans (invoke_agent, execute_tool, call_llm).
  • Decide between KNN, HNSW, ScaNN (AUTO vs. MANUAL, SQ8 vs. AH vs. FLAT), GIN/RUM/BM25, and ai.hybrid_search() vs. raw SQL CTEs based on scale, selectivity, and recall targets.
  • Build an end-to-end hybrid retrieval, Discovery Engine reranking (ai.rank()), and two-layer RAG evaluation loop gated by evaluate_query_recall(), Recall/NDCG, and GROUNDING/HALLUCINATION.

Setup

To run every SQL statement and Python evaluation pattern in this guide, provision an AlloyDB for PostgreSQL cluster running PostgreSQL 17 or higher (required for pg_textsearch BM25 indexes and GA Columnar Engine HNSW caching, and supporting up to 104,857,600 ScaNN leaves vs. 30,000,000 on PostgreSQL 16 and earlier).

First, enable the Vertex AI (aiplatform.googleapis.com) and Discovery Engine (discoveryengine.googleapis.com) APIs, and grant the AlloyDB service agent the two IAM roles it needs for zero-secret, in-database embedding and reranking calls:

gcloud services enable aiplatform.googleapis.com discoveryengine.googleapis.com \
  --project=PROJECT_ID

gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="serviceAccount:service-PROJECT_NUMBER@gcp-sa-alloydb.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"

gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="serviceAccount:service-PROJECT_NUMBER@gcp-sa-alloydb.iam.gserviceaccount.com" \
  --role="roles/discoveryengine.viewer"
Enter fullscreen mode Exit fullscreen mode

IAM bindings take 60 seconds to 7 minutes to propagate. Next, turn on the database flags for the AI query engine, preview AI functions (ai.hybrid_search()), Columnar Engine index caching, and ScaNN adaptive filtering:

gcloud alloydb instances update INSTANCE_ID \
  --cluster=CLUSTER_ID \
  --region=us-central1 \
  --project=PROJECT_ID \
  --database-flags=google_ml_integration.enable_ai_query_engine=on,google_ml_integration.enable_preview_ai_functions=on,google_ml_integration.enable_faster_embedding_generation=on,google_columnar_engine.enabled=on,google_columnar_engine.enable_index_caching=on,scann.enable_preview_features=on
Enter fullscreen mode Exit fullscreen mode

Note that google_columnar_engine.enabled and scann.enable_preview_features trigger an instance restart when changed. Connect to your primary instance as a member of alloydbsuperuser (required to run CREATE EXTENSION) and install the extensions:

CREATE EXTENSION IF NOT EXISTS alloydb_scann CASCADE;
CREATE EXTENSION IF NOT EXISTS google_ml_integration;
CREATE EXTENSION IF NOT EXISTS pg_textsearch;

SELECT extname, extversion
FROM pg_extension
WHERE extname IN ('vector', 'alloydb_scann', 'google_ml_integration', 'pg_textsearch', 'google_columnar_engine');
Enter fullscreen mode Exit fullscreen mode

Installing alloydb_scann with CASCADE automatically installs AlloyDB's customized vector extension (0.8.5.google-1, which includes evaluate_query_recall() from 0.8.0.google-3 onward) alongside alloydb_scann (0.1.3). Verify google_ml_integration is 1.5.6 or later (1.6.4 is the latest supported version) so both ai.rank() (1.5.2+) and ai.initialize_embeddings() (1.5.6+) are available. If you are on PostgreSQL 16 or earlier where pg_textsearch is unavailable, substitute CREATE EXTENSION IF NOT EXISTS rum; (1.3).


Part A: The production hybrid RAG topology on AlloyDB

Before tuning any index knob, map out where work runs at query time. A common mistake in early RAG stacks is splitting operational metadata into PostgreSQL, vectors into a separate managed vector store, lexical search into a standalone search cluster, and reranking into application glue code. Every network hop adds serialization overhead, eventual-consistency lag after writes, and a new security perimeter to govern.

AlloyDB collapses the retrieval data plane into one PostgreSQL cluster while keeping compute, model inference, and observability cleanly separated:

Production Hybrid RAG Architecture on AlloyDB and Google Cloud showing Cloud Run ADK and LangChain calling ai.hybrid_search() on AlloyDB PG 17+ with ScaNN, pg_textsearch BM25, Columnar Engine, google_ml_integration, Vertex AI Embeddings, Discovery Engine semantic-ranker-default-003, AlloyDB Service Agent IAM, Cloud Trace OTel spans, and recall/drift evals

Every retrieval stage runs inside one transactional PostgreSQL boundary on port 5432, authenticated to Vertex AI and Discovery Engine through the AlloyDB Service Agent with zero database-stored API keys.

Trace the five numbered paths in the diagram:

  1. RAG Prompt (Step 1): A user or upstream agent sends a natural-language prompt and structured SQL filters (tenant, price, category, timestamp) to an Agent Development Kit (ADK) or langchain-google-alloydb-pg service on Cloud Run.
  2. In-Database Hybrid Search (Step 2): Cloud Run invokes ai.hybrid_search() (directly in SQL or through AlloyDBVectorStore configured with HybridSearchConfig) over port 5432, hitting Primary or Read Pool instances running PostgreSQL 17+.
  3. Query Vectorization (Step 3): Only the user query is embedded at request time via ai.embedding('gemini-embedding-001', ...) inside google_ml_integration (1.6.4 latest; 1.5.6+ required), authenticated by the AlloyDB Service Agent (roles/aiplatform.user).
  4. Cross-Encoder Reranking (Step 4): The fused top-M candidate pool is rescored inside SQL via ai.rank() calling Discovery Engine's semantic-ranker-default-003 (discoveryengine.googleapis.com) in under 100 ms using roles/discoveryengine.viewer.
  5. Grounded Synthesis and Telemetry (Step 5): Only the top-K grounded chunks return to Cloud Run to condition the Gemini generation call. Simultaneously, Cloud Run exports OpenTelemetry spans (invoke_agent, call_llm, execute_tool) to Cloud Trace, while AI and database engineers run evaluate_query_recall() and inspect pg_stat_ann_indexes out of band.

Batch vs. inline embeddings at table scale

For small demo tables (under 100k rows), a GENERATED ALWAYS AS (embedding('text-embedding-005', description)) STORED column keeps vectors synchronized inline. Above 100,000 rows, the AlloyDB docs advise against inline generated columns for existing data because row-by-row remote calls saturate quotas and stall writes. Instead, create your table with a tsvector column for lexical search, metadata columns for B-tree filtering, and a nullable vector(DIMENSION) column (DEFAULT NULL). Then run ai.initialize_embeddings() with batching (batch_size => 50), which handles transient quota retries and exposes progress through ai.embedding_progress_view:

CREATE TABLE documents (
  doc_id TEXT PRIMARY KEY,
  content TEXT NOT NULL,
  price NUMERIC(10, 2) NOT NULL DEFAULT 0,
  text_tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
  text_embedding vector(3072) DEFAULT NULL
);

CALL ai.initialize_embeddings(
  model_id => 'gemini-embedding-001',
  table_name => 'documents',
  content_column => 'content',
  embedding_column => 'text_embedding',
  batch_size => 50
);
Enter fullscreen mode Exit fullscreen mode

When source rows change later, keep vectors fresh with ai.refresh_embeddings() (or configure incremental_refresh_mode => 'transactional' only if your write volume tolerates synchronous scalar transform calls). Remember the embedding immutability rule: the embedding model used at query time in ai.embedding() must match the exact model and dimensionality stored in the column, or cosine distances become meaningless.


Part B: ScaNN internals vs. pgvector HNSW

Predict before you check: why HNSW hits a RAM wall

Suppose your corpus grows from 5 million to 150 million 768-dimensional float32 vectors (roughly 460 GB of raw floats alone, before index overhead). Both pgvector HNSW and AlloyDB ScaNN are available on the same vector column. Which index fails first when index size exceeds instance RAM, and why does INSERT throughput diverge between the two?

Architectural comparison of pgvector HNSW multi-layer pointer graph versus AlloyDB ScaNN 2- to 4-level partitioned K-means tree, AUTO and MANUAL modes, PCA plus SQ8/AH/FLAT quantization pipeline, and verified ScaNN gains

HNSW traverses bidirectional pointers across RAM-hungry graph layers, whereas ScaNN prunes a K-means tree down to contiguous leaf partitions and scans quantized codes sequentially.

Answer: pgvector HNSW degrades sharply as soon as its graph spills out of memory. HNSW stores uncompressed vectors plus multi-layer bidirectional adjacency pointer lists in memory; traversing random-access pointers across disk pages triggers heavy random I/O, and every INSERT or UPDATE must rewire neighbor edge lists across layers (m, ef_construction). HNSW's practical sweet spot in AlloyDB is 10 to 20 million vectors when the graph fits largely in memory cache (and note that refreshing a Columnar-Engine-accelerated HNSW index can temporarily consume up to 2x index memory).

AlloyDB ScaNN (Scalable Nearest Neighbors) flips the data structure from a pointer graph to a 2- to 4-level partitioned K-means search tree combined with quantization and PCA reduction. When a query arrives, ScaNN compares the query vector against top-level centroids, prunes away irrelevant branches, and scans only scann.num_leaves_to_search contiguous leaf partitions sequentially.

Across AlloyDB's index strategy benchmarks against standard PostgreSQL pgvector HNSW, ScaNN delivers:

  • 3x to 4x less memory footprint (3x documented on the vector search overview; up to 4x less memory in the index strategy guide via SQ8 / AH quantization and PCA).
  • Up to 6x faster vector queries (and up to 4x in earlier baselines) via sequential leaf scans instead of random pointer chasing.
  • Up to 10x faster filtered vector search using ScaNN-only inline bitmap filtering and Adaptive Filtering.
  • Up to 16x faster index creation (partitioned K-means clustering vs. incremental HNSW graph construction).
  • Up to 24x higher write throughput, scaling cleanly up to 10 billion vectors.

The three-stage compression and precision recovery pipeline

ScaNN keeps RAM small without throwing away recall by running three steps inside a single index scan:

  1. PCA Reduction (scann.enable_pca, enabled by default): High-dimensional embeddings retain most of their variance in a smaller subspace (AlloyDB docs note that ~90% of the information can often be retained in 20% of the dimensions). PCA compresses vectors inside the index to cut CPU and memory bandwidth. Disable scann.enable_pca = false at index creation only if you measure recall degradation on dense, uncorrelated vectors.
  2. Quantization (quantizer):
    • SQ8 (Default): 8-bit scalar quantization. Cuts footprint dramatically with typical recall loss under 1% to 2%.
    • FLAT: Uncompressed leaf codes. Use when strict 99% or higher recall outweighs memory and latency savings.
    • AH (Preview): Asymmetric hashing, compressed up to 4x further than SQ8. Pair with the Columnar Engine (google_columnar_engine.enabled=on) for maximum scan throughput at massive scale.
  3. Exact Re-Rank (scann.pre_reordering_num_neighbors): Because PCA and SQ8 introduce minor ranking approximation, ScaNN oversamples a candidate pool from the quantized leaf scans and re-scores them against the original uncompressed vectors before returning LIMIT K. When PCA is enabled, the default is 50 * K (for example, 500 candidates for LIMIT 10); otherwise the default is 0 (disabled). Raising this knob improves recall on 500+ dimension vectors at a modest QPS cost.

Choosing AUTO vs. MANUAL tree depth

For most workloads, MODE='AUTO' (the default) lets AlloyDB select partitions, maintain centroids (auto_maintenance=ON), and optimize for either SEARCH_OPTIMIZED (default: best recall and latency) or BALANCED (faster index build):

CREATE INDEX docs_scann_auto_idx ON documents
USING scann (text_embedding cosine)
WITH (MODE = 'AUTO', OPTIMIZATION = 'SEARCH_OPTIMIZED', auto_maintenance = 'ON');
Enter fullscreen mode Exit fullscreen mode

When you have strict latency/recall SLAs or >100M rows, switch to MODE='MANUAL' and size tree depth (max_num_levels) and num_leaves to your row count N (remembering scann.max_allowed_num_levels defaults to 2 and caps at 3, and auto_maintenance is unsupported on four-level trees):

Vector row count (N) Tree depth max_num_levels Balanced num_leaves formula Quality num_leaves ceiling
0 to 10M Two-level 1 (default) sqrt(N) N / 100
10M to 100M Two-level (recall) or Three-level (build speed) 1 or 2 sqrt(N) or power(N, 2/3) N / 100
100M to 1B Three-level (recall) or Four-level (build speed) 2 or 3 power(N, 2/3) or power(N, 3/4) N / 100
1B to 10B Four-level 3 power(N, 3/4) N / 100

Note the hard partition ceiling: num_leaves can be set up to 104,857,600 on PostgreSQL 17+ (documented as 100 million in the tuning overview) and 30,000,000 on PostgreSQL 16 and earlier. Also note a common Day-0 trap: ScaNN rejects CREATE INDEX on an empty table or a table with fewer rows than num_leaves because training K-means centroids on tiny data ruins recall. For streaming ingestion on a fresh table, enable scann.enable_index_with_insufficient_data=on (or scann.enable_preview_features=on) alongside scann.enable_index_maintenance=on and WITH (MODE='AUTO') so AlloyDB defers the background index build until the table hits 10,000 rows (do not set scann.allow_blocked_operations = true in production; reserve that SUPERUSER override for unit tests).

If you build a manual index for a 10M-row table, monitor build phases with SELECT * FROM pg_stat_progress_create_index;, tune parallel workers (max_parallel_maintenance_workers), and keep maintenance_work_mem and shared_buffers below total machine RAM:

CREATE INDEX docs_scann_manual_idx ON documents
USING scann (text_embedding cosine)
WITH (
  mode = 'MANUAL',
  num_leaves = 46416,
  max_num_levels = 2,
  quantizer = 'SQ8',
  auto_maintenance = 'ON'
);
Enter fullscreen mode Exit fullscreen mode

Once built, tune scann.num_leaves_to_search (default 1% of num_leaves if both num_leaves_to_search and pct_leaves_to_search are 0) and scann.pre_reordering_num_neighbors per session with SET LOCAL without rebuilding the index.


Part C: Filtered vector search, adaptive filtering, and Columnar Engine caching

Predict before you check: why selective WHERE clauses return fewer than K rows

Suppose your table has 10 million products indexed with ScaNN (num_leaves = 10000, scann.num_leaves_to_search = 100). A user runs WHERE price <= 10 ORDER BY embedding <=> q LIMIT 10. Only 0.05% of products cost $10 or less. If AlloyDB scans the 100 closest leaves to q and applies WHERE price <= 10 afterward, what happens?

Filtered Vector Search Execution Flow showing naive post-filtering returning only 2 of 10 rows versus AlloyDB Adaptive Filtering switching between ScaNN-only Inline Filtering with scann.satisfy_limit streaming and Pre-Filtering Fallback, accelerated by Columnar Engine Ultra-Fast Cache

Naive post-filtering discards 80% of candidates and stops short; Adaptive Filtering pairs a Metadata Bitmap Scan with runtime selectivity switching, streaming leaf expansion, and an in-memory Columnar Engine cache.

Answer: Post-filtering drops most candidates after distances are already computed, leaving you with 2 rows instead of 10 (insufficient recall) and wasted CPU work. Conversely, if you always force pre-filtering on a loose filter like WHERE price <= 1000 (95% of rows), PostgreSQL wastes time materializing a massive row list and loses the ScaNN index altogether, falling back to a slow exact KNN scan over 9.5 million vectors.

AlloyDB solves both sides of this trap with three cooperating mechanisms:

  1. Inline Filtering (ScaNN-only): Create standard B-tree or GIN indexes on your metadata filter columns (CREATE INDEX idx_docs_price ON documents (price);). PostgreSQL executes a Bitmap Index Scan to build a candidate row bitmap, and ScaNN computes distances only on bitmap-matched rows inside visited leaves (Execution Strategy: Bitmap assisted vector Scan on scann_idx). Remember: pgvector HNSW, IVF, and IVFFlat do not support inline filtering; highly selective filters on HNSW can exhaust hnsw.max_scan_tuples or degrade recall.
  2. Adaptive Filtering (Preview via scann.enable_preview_features=on): Planner table statistics are often stale or skewed. Adaptive Filtering monitors real-time filter selectivity during query execution. If the filter is loose (price <= 1000), it stays on ScaNN inline filtering. If it detects high selectivity (price <= 10) mid-execution, it pivots dynamically to Execution Strategy: Bitmap assisted pre-filtering, narrows the tiny matching row set first, and runs an exact KNN scan over those few rows.
  3. Streaming Leaf Expansion + Overshoot Cap: When inline filtering returns fewer than LIMIT K rows inside the initial num_leaves_to_search, enable streaming expansion:
SET LOCAL scann.satisfy_limit = 'relaxed_order';
SET LOCAL scann.max_num_leaves_to_search_pct = 15;
Enter fullscreen mode Exit fullscreen mode

With scann.satisfy_limit = 'relaxed_order', ScaNN streams into additional leaves until K compliant rows are found or until it hits scann.max_num_leaves_to_search_pct (default 15% of total leaves). That 15% cap exists for a mathematical reason: once an ANN scan has to inspect more than 15% of all partitions, ANN pruning no longer beats pre-filtered exact KNN.

Accelerating vector scans with the Columnar Engine Ultra-Fast Cache

Even with SQ8 quantization, reading index pages from storage slows cold-tail latency. AlloyDB's Columnar Engine includes an Ultra-Fast Cache for vector indexes (GA on PostgreSQL 17+ for HNSW at up to 5x faster queries; Preview for ScaNN):

SELECT google_columnar_engine_add_index('docs_scann_auto_idx');
SELECT * FROM g_columnar_indexes;
Enter fullscreen mode Exit fullscreen mode

Always confirm cache engagement in EXPLAIN (ANALYZE, COLUMNAR_ENGINE) rather than assuming it is active. For ScaNN (Preview), the AlloyDB docs (accelerate-with-ce.md) show what to look for in the plan node:

/* Documented reference EXPLAIN output from AlloyDB accelerate-with-ce.md */
Index Scan using scann_idx on t t_1 (actual rows=100 loops=1)
     Order By: (val <=> '[0.5,0.5,0.5,0.5]'::vector)
     Limit: 100
     ScaNN Info: (... columnar engine nodes hit=6...)
     Columnar Engine ScaNN Info: (index found=true)
Enter fullscreen mode Exit fullscreen mode

For HNSW (GA PG 17+), check Columnar Engine HNSW Info: (index found=true elements_from_ce=385 elements_from_disk=0). Under heavy INSERT/UPDATE/DELETE traffic, valid vectors continue serving from cache while mutated rows fall back to disk (elements_from_disk > 0). Tune google_columnar_engine.refresh_threshold_percentage or call SELECT google_columnar_engine_refresh_index('docs_scann_auto_idx'); after bulk loads.


Part D: Hybrid search (ai.hybrid_search(), BM25 <@>, RRF) and <100 ms ai.rank()

Predict before you check: why BM25 <@> sorts ASC and why raw scores cannot be added

Vector cosine distance (<=>) lives in [0, 2], where 0 is an exact match. PostgreSQL ts_rank() and BM25 measure relevance differently, and pg_textsearch's BM25 operator <@> returns negative floats. Why does <@> return negative numbers, and why do both ai.hybrid_search() and raw SQL hybrid queries combine ranks with 1 / (60 + rank) instead of normalizing and adding raw scores?

Hybrid Search and Semantic Reranking Flow Inside AlloyDB SQL showing parallel Dense Semantic ScaNN branch and Sparse Lexical BM25/RUM branch merged by ai.hybrid_search() RRF into Top-M pool and rescored by ai.rank() semantic-ranker-default-003 in under 100ms

Dense ScaNN cosine distance and sparse BM25 or RUM scoring execute in parallel CTEs, fuse via Reciprocal Rank Fusion without score calibration, and pass a Top-M pool to the Discovery Engine cross-encoder.

Answer: PostgreSQL B-tree/index-ordered operator scans only accelerate ORDER BY ... ASC, so pg_textsearch negates BM25 scores to let the index stream the strongest matches (-0.997 before -0.210 before 0) first under ORDER BY content <@> q ASC. And raw cosine distances cannot simply be added to BM25 or ts_rank scores because their distributions shift wildly across queries and corpus lengths. Reciprocal Rank Fusion (RRF) (score = SUM(w_i / (60 + rank_i))) depends only on ordinal position rank_i with a smoothing constant of 60, requiring zero score calibration.

Choosing a lexical index: GIN vs. RUM vs. BM25 (pg_textsearch)

Lexical Index PostgreSQL Support Operator / Ranking Best For
GIN (to_tsvector) All versions @@ + ts_rank Standard keyword filters when table lookups are acceptable
RUM (rum 1.3) All versions (PG 18 and earlier) @@ + <=> distance Faster phrase search, timestamp addon sorts (rum_tsvector_addon_ops), avoiding heap fetches
BM25 (pg_textsearch 1.3, Preview) PG 17 and 18 only <@> (negative score, ASC) Probabilistic Term Frequency saturation (k1=1.2) and Document Length normalization (b=0.75)

To create a BM25 index alongside your ScaNN index on PostgreSQL 17+:

CREATE INDEX docs_bm25_idx ON documents
USING bm25 (content)
WITH (text_config = 'english', k1 = 1.2, b = 0.75);
Enter fullscreen mode Exit fullscreen mode

Increase k1 (for example 1.5) when repeated query terms should keep boosting relevance; increase b (for example 0.8) to penalize long, noisy documents more aggressively.

Option 1: Single-call ai.hybrid_search()

When using GIN (text_tsv generated column) or RUM (ranking_function => '<=>'), ai.hybrid_search() dynamically builds parallel CTEs, defaults to AlloyDB's enhanced ai.g_to_tsquery() parser, performs the RRF FULL OUTER JOIN, and optionally emits per-component timing and score breakdowns via include_json_output => true:

SELECT id, score
FROM ai.hybrid_search(
  search_inputs => ARRAY[
    '{
      "data_type": "vector",
      "weight": 0.5,
      "table_name": "documents",
      "key_column": "doc_id",
      "vec_column": "text_embedding",
      "distance_operator": "public.<=>",
      "limit": 25,
      "query_vector": "ai.embedding(''gemini-embedding-001'', ''enterprise vector search'')::vector"
    }'::JSONB,
    '{
      "data_type": "text",
      "weight": 0.5,
      "table_name": "documents",
      "key_column": "doc_id",
      "text_column": "text_tsv",
      "limit": 25,
      "ranking_function": "ts_rank",
      "query_text_input": "enterprise vector search"
    }'::JSONB
  ],
  id_type => NULL::TEXT,
  include_json_output => false
);
Enter fullscreen mode Exit fullscreen mode

Always pass id_type matching your key_column type (for example NULL::INTEGER for integer IDs, default NULL::TEXT) to avoid implicit cast mismatches.

Option 2: Raw SQL RRF (BM25 <@>) chained into ai.rank()

Because pg_textsearch BM25 uses <@> rather than ts_rank, raw SQL CTEs let you combine ScaNN + BM25 RRF (Top-M, M = 20 to 50) and immediately pipe the surviving candidates into Discovery Engine's ai.rank() cross-encoder (semantic-ranker-default-003) in a single database round trip:

WITH vector_search AS (
  SELECT doc_id,
         RANK() OVER (ORDER BY text_embedding <=> ai.embedding('gemini-embedding-001', 'enterprise vector search')::vector) AS rank
  FROM documents
  ORDER BY text_embedding <=> ai.embedding('gemini-embedding-001', 'enterprise vector search')::vector
  LIMIT 25
),
text_search AS (
  SELECT doc_id,
         RANK() OVER (ORDER BY content <@> 'enterprise vector search' ASC) AS rank
  FROM documents
  ORDER BY content <@> 'enterprise vector search' ASC
  LIMIT 25
),
rrf_pool AS (
  SELECT COALESCE(v.doc_id, t.doc_id) AS doc_id,
         COALESCE(1.0 / (60 + v.rank), 0.0) + COALESCE(1.0 / (60 + t.rank), 0.0) AS rrf_score
  FROM vector_search v
  FULL OUTER JOIN text_search t ON v.doc_id = t.doc_id
  ORDER BY rrf_score DESC
  LIMIT 30
),
ranked_input AS (
  SELECT d.doc_id, d.content, r.rrf_score,
         ROW_NUMBER() OVER (ORDER BY r.rrf_score DESC) AS ref_number
  FROM rrf_pool r
  JOIN documents d ON d.doc_id = r.doc_id
),
reranked AS (
  SELECT index, score
  FROM ai.rank(
    model_id => 'semantic-ranker-default-003',
    search_string => 'enterprise vector search',
    documents => (SELECT ARRAY_AGG(content ORDER BY ref_number) FROM ranked_input),
    top_n => 5
  )
)
SELECT i.doc_id, i.content, rr.score AS ranker_score, i.rrf_score
FROM ranked_input i
JOIN reranked rr ON i.ref_number = rr.index
ORDER BY rr.score DESC;
Enter fullscreen mode Exit fullscreen mode

Why pay for ai.rank() when you already ran RRF? RRF only sees rank positions from independent bi-encoder and lexical passes; it never compares the query and document tokens jointly. A cross-encoder (semantic-ranker-default-003) scores full query-document attention in under 100 ms (compared to 1 to 2 seconds and higher token cost for an LLM-based reranker), pushing the exact relevant chunk from rank 9 to rank 1 before Gemini ever sees the context. Note that ai.rank() returns a 1-based index into the documents array, so ORDER BY ref_number inside ARRAY_AGG is mandatory to join scores back to the right rows.


Part E: Two-layer RAG evals, OpenTelemetry isolation, and ScaNN drift

Predict before you check: why one eval score hides the real bug

Your RAG agent answers "I do not have information about warranty exclusions," even though reviewers verify the warranty PDF is in AlloyDB. Meanwhile, an autorater checks the refusal against retrieved chunks and scores GROUNDING = 1.0. Why did GROUNDING pass, and which two evaluation gates must stay separate to localize this failure?

Two-Layer Agentic RAG Evaluation, OpenTelemetry Span Isolation, and Vector Index Drift Loop showing Layer 1 Retrieval Gate (evaluate_query_recall(), Recall, NDCG, Precision), Layer 2 Generation Gate (HALLUCINATION, GROUNDING, tool trajectory), Cloud Trace OTel waterfall (invoke_agent -> execute_tool -> call_llm), and pg_stat_ann_indexes drift loop triggering AUTO maintenance or REINDEX CONCURRENTLY

Never blame the LLM before checking retrieval: Layer 1 certifies index recall and ranking (Recall, NDCG), Layer 2 certifies tool trajectory and groundedness (HALLUCINATION, GROUNDING), and Cloud Trace OTel spans isolate latency and ReAct logic.

Answer: GROUNDING only checks whether the generated text contradicts the provided source context; a polite refusal or a faithful summary of the wrong retrieved chunks scores well on GROUNDING. If the right warranty chunk was never retrieved, no prompt edit can fix the answer. You must split evaluation into two layers, backed by two distinct golden datasets:

Layer 1: Retrieval Quality Gate (AlloyDB + Search Quality Eval)

First, benchmark your ScaNN index itself inside PostgreSQL with evaluate_query_recall() (available in vector 0.8.0.google-3+, enabled by default, with enable_indexscan = on):

SELECT *
FROM evaluate_query_recall(
  $$ SELECT doc_id FROM documents ORDER BY text_embedding <=> ai.embedding('gemini-embedding-001', 'warranty exclusions')::vector LIMIT 10 $$,
  '{"scann.num_leaves_to_search": 10, "scann.pre_reordering_num_neighbors": 500}',
  ARRAY['scann']
);
Enter fullscreen mode Exit fullscreen mode

In the documented reference output from measure-vector-query-recall.md, evaluate_query_recall() returns recall, ann_execution_time, and ground_truth_execution_time (sequential scan baseline) side by side so you can compare index configurations without guessing. Watch two documented caveats: if a selected column can be NULL, wrap it in COALESCE (or select only doc_id), and if evaluate_query_recall() prints NOTICE: Recall is 1, check whether the planner skipped the ScaNN index and fell back to sequential scan.

Second, measure end-to-end retrieval and ranking quality against a fixed sample query set (Queries paired with Targets, the expected document URIs, up to 20,000 queries) using three metrics:

  • Recall: Of the target documents, how many appeared in Top-M? Low recall points to chunking, embedding mismatch, narrow top_k, or a stale/under-probed ScaNN index.
  • Precision: Of the retrieved documents, how many were true targets? Low precision points to missing SQL filters or noisy lexical expansion.
  • NDCG (Normalized Discounted Cumulative Gain): Are the target documents ranked near the top with position discounting? High recall + low NDCG is the exact signature that justifies adding ai.rank() (semantic-ranker-default-003).

Layer 2: Generation Quality Gate and OTel Span Isolation

Once Layer 1 passes, evaluate the ADK agent against eval cases containing prompts, reference answers, and expected intermediate tool trajectories:

  • tool_trajectory_avg_score: Verifies whether the agent actually called your AlloyDB hybrid search tool with the right arguments (EXACT, IN_ORDER, or ANY_ORDER).
  • final_response_match_v2 vs. response_match_score: Prefer LLM-judged semantic match (final_response_match_v2) when valid paraphrasing makes deterministic ROUGE-1 (response_match_score) artificially low.
  • GROUNDING vs. HALLUCINATION (types.RubricMetric): Both are static rubrics. GROUNDING verifies factuality against a provided source text (essential for RAG), while HALLUCINATION segments the answer into atomic claims and verifies each claim against what the agent's tools actually returned in intermediate events. Using both catches unsupported claims even when a tool returns partial context.

When latency spikes or trajectories drift, inspect Cloud Trace OpenTelemetry spans exported by ADK (--otel_to_cloud in adk web or adk deploy agent_engine). ADK nests spans into a waterfall: root invoke_agent {agent.name} containing child model spans (call_llm / generate_content {model.name} for both query embedding and LLM synthesis) and execute_tool {tool.name} (wrapping your ai.hybrid_search() and ai.rank() SQL execution). In production on Cloud Run, set ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=false so raw prompts and customer documents are redacted to {} / N/A in traces, and reserve detailed ReAct Thought -> Action -> Observation logging for isolated staging diagnostics.

Closing the loop: ScaNN drift & skew monitoring via pg_stat_ann_indexes

Even if your model and prompts never change, INSERT, UPDATE, and DELETE mutations shift your vector distribution over time, degrading Layer 1 recall. Query pg_stat_ann_indexes joined with pg_stat_ann_index_creation on a schedule:

SELECT i.indexrelname,
       i.indextype,
       i.partitioncount,
       i.insertcount,
       i.updatecount,
       i.deletecount,
       c.index_rows_at_creation_time,
       i.distribution->>'maximum' AS max_leaf_vecs,
       i.distributionpercentile->'50'->>'num_vectors' AS p50_leaf_vecs
FROM pg_stat_ann_indexes i
JOIN pg_stat_ann_index_creation c USING (indexrelid);
Enter fullscreen mode Exit fullscreen mode

The AlloyDB docs (vector-index-metrics.md) define exact numeric thresholds for when an index has drifted or skewed:

  • High data mutation: Current row count (pg_class.reltuples) exceeds 2x index_rows_at_creation_time (without auto_maintenance), 3x (with auto_maintenance=ON), drops below 0.5x, or total mutations (insertcount + updatecount + deletecount) exceed 2x index_rows_at_creation_time.
  • Skewed outlier leaves: Some variance (5x to 10x max-to-median leaf ratio) is normal from K-means clustering at build time, but a 50x to 100x ratio between the 100th percentile (maximum) and 50th percentile (median) signals hot partitions dragging down QPS and recall.

When auto_maintenance=ON is active, AlloyDB's background workers (scann.max_background_workers) split outlier leaves and update centroids automatically. Pair auto_maintenance=ON with ALTER DATABASE ... SET scann.pct_leaves_to_search = 1; so the scan count scales proportionally as partitions split. After major bulk mutations, rebuild online without blocking reads or writes, refresh the Columnar Engine cache, and re-run Layer 1 recall before promoting changes:

REINDEX INDEX CONCURRENTLY docs_scann_auto_idx;
SELECT google_columnar_engine_refresh_index('docs_scann_auto_idx');
Enter fullscreen mode Exit fullscreen mode

Part F: Wiring Cloud Run, langchain-google-alloydb-pg, and the eval gate

In application code, you can invoke ai.hybrid_search() + ai.rank() directly over an async pg / asyncpg pool (using the AlloyDB Python Connector IAM auth pattern from Part 1), or initialize AlloyDBVectorStore from langchain-google-alloydb-pg alongside HybridSearchConfig for LangChain pipelines:

from langchain_google_alloydb_pg import AlloyDBVectorStore

# engine = AlloyDBEngine.from_instance(...) configured with IAM auth
# embeddings_service = VertexAIEmbeddings(model_name="gemini-embedding-001")
vs = await AlloyDBVectorStore.create(
    engine=alloydb_engine,
    embedding_service=embeddings_service,
    table_name="documents",
)
# Enable hybrid search by attaching HybridSearchConfig in AlloyDBVectorStore.create(...)
Enter fullscreen mode Exit fullscreen mode

On the evaluation side, run Vertex AI Evaluation Service static rubrics in CI/CD before promoting a new Cloud Run revision or ScaNN index configuration:

from vertexai import evals, types

result = client.evals.evaluate(
    dataset=eval_dataset,
    metrics=[
        types.RubricMetric.FINAL_RESPONSE_QUALITY,
        types.RubricMetric.TOOL_USE_QUALITY,
        types.RubricMetric.HALLUCINATION,
        types.RubricMetric.GROUNDING,
        types.RubricMetric.SAFETY,
    ],
)
Enter fullscreen mode Exit fullscreen mode

Deploy the Cloud Run service with explicit least-privilege IAM (roles/alloydb.client, never roles/alloydb.admin, for inbound connectivity) and OpenTelemetry span safety (ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=false when deploying outside adk deploy agent_engine --otel_to_cloud), gating rollout only when both Layer 1 (evaluate_query_recall() + Recall/NDCG) and Layer 2 (GROUNDING/HALLUCINATION + tool trajectory) pass.


Decision table

If you see... Use... Because...
Fewer than 100k vectors and strict 100% exactness Unindexed KNN + Columnar Engine (google_columnar_engine_add()) Brute-force KNN guarantees 100% recall and fits in columnar memory
10M to 20M vectors fitting in RAM, no inline filtering HNSW + Columnar Engine (GA PG 17+) Up to 5x faster than standard HNSW when elements_from_disk=0
>20M to 10B vectors, heavy writes, or selective WHERE filters ScaNN (MODE='AUTO' or 3/4-level MANUAL, SQ8 or AH) 3x to 4x less memory, up to 24x write throughput, inline bitmap filtering
SQ8 recall slightly below target on 500+ dim vectors Raise scann.pre_reordering_num_neighbors (>= 50 * K) or quantizer='FLAT' Re-scores more candidates with uncompressed vectors (FLAT reaches >=99%)
WHERE filter returns fewer than LIMIT K rows scann.satisfy_limit = 'relaxed_order' + B-tree/GIN index + scann.enable_preview_features=on Streams leaves up to scann.max_num_leaves_to_search_pct (15%) or pivots to pre-filtering
Semantic search misses SKUs, IDs, or exact keywords ai.hybrid_search() or BM25 <@> (pg_textsearch PG 17/18) + RRF Combines dense semantic cosine (<=>) with lexical scoring without score calibration
High Layer 1 Recall but low NDCG (right chunk buried at rank 9) ai.rank('semantic-ranker-default-003', ...) over Top-M RRF pool Cross-encoder rescoring boosts top-K precision in <100 ms
Agent says "cannot find it" while GROUNDING is high Layer 1 eval (evaluate_query_recall() + Recall/NDCG) Retrieval missed the chunk; prompt edits cannot fix missing context
insertcount + updatecount + deletecount > 2x creation rows or 50x leaf skew REINDEX INDEX CONCURRENTLY + google_columnar_engine_refresh_index() Rebalances K-means partitions and clears stale Columnar Engine entries

Try it yourself

  1. Map your own Recall vs. QPS frontier. Load 100,000+ vectors into a test table, create an AUTO ScaNN index (SQ8) and a MANUAL ScaNN index (FLAT), and run evaluate_query_recall() across scann.num_leaves_to_search values of 5, 20, and 100 with scann.pre_reordering_num_neighbors at 50 * K vs. 10 * K. Record recall, ann_execution_time, and ground_truth_execution_time.
  2. Trigger the Adaptive Filtering switch. Create a B-tree index on a numeric price column alongside your ScaNN index with scann.enable_preview_features=on. Run EXPLAIN (ANALYZE, SCANN) on a query with WHERE price <= 1000 (low selectivity) and then WHERE price <= 10 (high selectivity). Compare Execution Strategy (Bitmap assisted vector Scan vs. Bitmap assisted pre-filtering), and verify that scann.satisfy_limit = 'relaxed_order' restores full LIMIT 10 rows when price <= 10 would otherwise under-return.
  3. Fault-localize a two-layer RAG regression. Wire the Part D ai.hybrid_search() + ai.rank() query behind an ADK tool, capture a golden sample query set (10 queries + target doc_ids) and 10 eval cases, then intentionally sabotage retrieval (SET LOCAL scann.num_leaves_to_search = 1; and RESET scann.satisfy_limit;) vs. sabotage generation (instruct the prompt to ignore doc_id rules). Confirm that Layer 1 (Recall/NDCG) isolates the first fault while Layer 2 (GROUNDING/HALLUCINATION) isolates the second.

If you build something on top of this, post it with #AlloyDBSprint.


What's next

You now have a fast, recall-verified, hybrid RAG data plane running inside AlloyDB. Part 3 tackles the security and cost frontier when autonomous agents query that data directly: enforcing row-level multi-tenancy with Parameterized Secure Views, inspecting prompts and SQL tool calls through Model Armor and IAM gates, and accelerating in-SQL LLM inference by orders of magnitude with AI Query Engine Smart Batching and proxy models.

Sources and further reading

Top comments (0)