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" 

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 

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'); 

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 ); 

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'); 

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' ); 

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; 

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; 

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) 

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); 

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 ); 

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; 

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...