cancel
Showing results for 
Search instead for 
Did you mean: 
Community Articles
Dive into a collaborative space where members like YOU can exchange knowledge, tips, and best practices. Join the conversation today and unlock a wealth of collective wisdom to enhance your experience and drive success.
cancel
Showing results for 
Search instead for 
Did you mean: 

Lakebase Search: Vector, Keyword, and Hybrid Retrieval Inside Databricks Postgres

Isaac_18
Contributor

Lakebase Search brings vector search and BM25 keyword search directly into Lakebase, Databricks’ managed, serverless PostgreSQL offering.

It introduces two PostgreSQL extensions:

  • lakebase_vector — Approximate nearest-neighbor (ANN) vector search, compatible with pgvector.
  • lakebase_text — BM25 keyword search, compatible with PostgreSQL tsvector.

Together, these extensions enable semantic, keyword, and hybrid retrieval using SQL in the same database that stores your operational data.

In this post, we’ll explore how Lakebase Search works, when to use each retrieval mode, and how to build a working search implementation with SQL.

1. The Problem: Search Often Requires Multiple Systems

Modern applications commonly need three types of search:

                                                                                           
Search mode Question it answersExample query
KeywordWhich records contain these exact terms?SKU-12345, an error code
Semantic (vector)Which records have a similar meaning?“A fantasy book about a boy wizard”
HybridWhich records are relevant by both meaning and keywords?“Harry Potter magic school adventure”

PostgreSQL has long provided reliable transactional capabilities, built-in full-text search, and vector search through extensions such as pgvector.

However, at scale, teams often operate three separate systems:

  • A transactional database for application data
  • A keyword search engine, such as Elasticsearch or OpenSearch
  • A vector database for semantic retrieval

This architecture introduces several challenges:

  • Data synchronization: Multiple copies of the same data must remain consistent, and delayed pipelines can produce stale search results.
  • Operational complexity: Teams must manage multiple query languages, APIs, indexes, and compute resources.
  • Multi-step retrieval: Applications may need to generate embeddings, query multiple search systems, merge results in application code, and retrieve complete records from PostgreSQL.
  • Additional infrastructure costs: Separate systems introduce duplicated storage and operational overhead.

Lakebase Search aims to simplify this architecture by bringing keyword and vector retrieval into the same PostgreSQL database, using SQL as the common interface.

2. What Does Lakebase Search Provide?

Lakebase Search introduces two extensions that support different retrieval strategies.


ExtensionPurposeIndex type
lakebase_vectorANN vector search with pgvector-compatible types, operators, and syntaxlakebase_ann
lakebase_textBM25 keyword search using PostgreSQL tsvectorlakebase_bm25

Vector search

The vector search index uses IVF partitioning with RaBitQ quantization.

Key characteristics include:

  • Storage-backed indexes that persist across scale-to-zero events.
  • Support for large vector indexes.
  • Faster index-building potential compared with HNSW-based approaches, depending on workload and configuration.
  • Familiar pgvector-compatible vector types and operators.

Databricks positions the technology for very large indexes, including workloads with more than one billion vectors. Consult the official documentation for benchmark results and the conditions under which these performance claims apply.

Keyword search with BM25

BM25 is a ranking algorithm that considers term frequency, document length, and corpus-wide statistics.

PostgreSQL’s built-in ts_rank does not use corpus-wide inverse document frequency statistics in the same way. This can affect relevance ranking for large document collections.

Lakebase Search also uses Block-Max WAND to efficiently retrieve top-ranked results without scoring every matching document.

Hybrid search

Hybrid search combines vector similarity and keyword relevance in a single SQL statement.

There is no separate hybrid operator. Instead, you can retrieve candidates from both search methods and combine their rankings using an algorithm such as Reciprocal Rank Fusion (RRF).

We’ll implement this in Section 6.

3. Before You Start

Before enabling Lakebase Search, check the following prerequisites:

  • PostgreSQL version: PostgreSQL 16 or later.
  • Feature availability: Lakebase Search is a Beta feature.
  • Permissions: A workspace administrator must enable the feature through the Previews page.
  • Project configuration: Enable Lakebase Search under Settings → Lakebase Search in your project.
Important: Enabling Lakebase Search is irreversible according to the feature guidance described here and restarts all computes in the project, dropping active connections. Test it in a disposable project before enabling it in a production environment.

After enabling the feature, install the extensions:

CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
CREATE EXTENSION IF NOT EXISTS lakebase_text;

The CASCADE option installs the required pgvector dependency for lakebase_vector.

4. Vector Search with lakebase_vector

Vector search retrieves records based on the similarity between numerical embeddings.

Each record stores an embedding in a VECTOR(n) column, where n must match the embedding model’s output dimension. The table column, index configuration, and query vector must all use compatible dimensions and distance metrics.

Choosing a distance metric

MetricOperator classOperator Typical Use case
Cosine distancevector_cosine_ops<=>Text embeddings and semantic search
L2 (Euclidean) distancevector_l2_ops<->Workloads where absolute geometric distance matters
Negative inner productvector_ip_ops<#>Similarity ranking, especially with normalized vectors

Choose the metric based on how your embedding model is intended to be used. The index operator class and query operator must match.

Step 1: Create a table

CREATE TABLE items (
    id        BIGSERIAL PRIMARY KEY,
    embedding VECTOR(3)
);

The three-dimensional vector is used here only to keep the example small. In a real application, use the dimension produced by your embedding model, such as 384 or another supported dimension.

Step 2: Insert sample embeddings

INSERT INTO items (embedding)
SELECT ARRAY[random(), random(), random()]::real[]
FROM generate_series(1, 1000);

This generates synthetic vectors for demonstration purposes. It does not generate meaningful semantic embeddings.

Step 3: Create an ANN index

CREATE INDEX ON items
USING lakebase_ann (embedding vector_l2_ops);

For larger datasets, building the index after bulk-loading data can be more efficient than creating it before the initial load.

Step 4: Query the nearest neighbors

SELECT *
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;

This query returns the five nearest vectors using L2 distance.

Tuning and utility functions

Lakebase Search exposes options for managing index-building performance and query-time recall.

  • build_mode = 'fast': Can accelerate index builds at the expense of recall. The standard build mode prioritizes recall.
  • lakebase_ann.probes: Increasing the number of probes can improve recall, generally at the cost of query latency.
  • lakebase_ann.epsilon: Controls the re-ranking margin. The documented range is 0.0–4.0, with a default of 1.9.
  • lakebase_ann_prewarm(regclass): Loads an index into memory to help reduce cold-start latency.
  • lakebase_ann_index_info(regclass): Returns index metadata.

Verify the supported settings and their exact configuration syntax in the documentation for your Lakebase version.

5. Keyword Search with BM25

Vector search is useful for semantic similarity, but exact identifiers, product codes, error messages, and terminology often benefit from keyword retrieval.

Lakebase Search provides BM25 ranking through the lakebase_text extension.

Step 1: Create a table with a generated tsvector column

CREATE TABLE documents (
    id      SERIAL PRIMARY KEY,
    passage TEXT,
    vector  TSVECTOR GENERATED ALWAYS AS (
        to_tsvector('english', passage)
    ) STORED
);

The generated column automatically maintains the text-search representation when the underlying passage changes.

Step 2: Insert sample documents

INSERT INTO documents (passage)
VALUES
    ('Postgres is a powerful open-source relational database.'),
    ('Vector search finds semantically similar results.'),
    ('BM25 ranking improves full-text search relevance scores.');

Step 3: Create a BM25 index

CREATE INDEX documents_passage_bm25
ON documents
USING lakebase_bm25 (vector);

Build the index after loading the initial dataset so that the index can calculate corpus statistics from the populated collection.

Step 4: Execute a keyword query

SELECT
    id,
    passage,
    vector <@> to_bm25query(
        to_tsvector('english', 'database'),
        'documents_passage_bm25'
    ) AS score
FROM documents
ORDER BY score
LIMIT 5;

The <@> operator returns a negative BM25 score, so ascending order places the most relevant results first.

Operational consideration: BM25 ranking depends on corpus statistics calculated during index construction. Review the documented behavior for inserts and updates, and determine whether your workload requires index maintenance or rebuilding to keep ranking quality aligned with the evolving dataset.

6. Hybrid Search with Reciprocal Rank Fusion (RRF)

Vector and keyword retrieval produce scores on different scales. Combining their raw scores directly can therefore be misleading.

Reciprocal Rank Fusion avoids this issue by combining the rank positions of documents rather than their raw scores.

The RRF formula is:

RRF⁡(d)=1k+rv(d)+1k+rk(d)\operatorname{RRF}(d) = \frac{1}{k+r_v(d)} + \frac{1}{k+r_k(d)}

Where:

  • dd is a document.
  • rv(d)r_v(d) is its rank in the vector results.
  • rk(d)r_k(d) is its rank in the keyword results.
  • kk is a smoothing constant, commonly set to 60.

A document appearing near the top of both result lists receives a stronger combined score.

Step 1: Create a table for both retrieval methods

CREATE TABLE docs (
    id        SERIAL PRIMARY KEY,
    title     TEXT NOT NULL,
    body      TEXT NOT NULL,
    embedding VECTOR(3),
    body_tsv  TSVECTOR GENERATED ALWAYS AS (
        to_tsvector('english', body)
    ) STORED
);

Step 2: Insert sample documents

INSERT INTO docs (title, body, embedding)
VALUES
    (
        'Postgres overview',
        'Postgres is an open-source relational database.',
        '[0.1, 0.2, 0.3]'
    ),
    (
        'Vector search guide',
        'Vector search finds semantically similar results.',
        '[0.4, 0.5, 0.6]'
    ),
    (
        'Full-text search',
        'BM25 ranking improves keyword search relevance.',
        '[0.7, 0.8, 0.9]'
    );

These embeddings are illustrative and are not intended to represent actual semantic relationships.

Step 3: Create both indexes

CREATE INDEX ON docs
USING lakebase_ann (embedding vector_cosine_ops);

CREATE INDEX docs_body_bm25
ON docs
USING lakebase_bm25 (body_tsv);

Step 4: Retrieve and fuse the results

The following query retrieves candidates from both methods, assigns ranks, and combines them using RRF.

WITH vector_ranked AS (
    SELECT
        id,
        RANK() OVER (ORDER BY dist) AS rank
    FROM (
        SELECT
            id,
            embedding <=> '[0.1, 0.2, 0.3]' AS dist
        FROM docs
        ORDER BY dist
        LIMIT 40
    ) v
),
keyword_ranked AS (
    SELECT
        id,
        RANK() OVER (ORDER BY score) AS rank
    FROM (
        SELECT
            id,
            body_tsv <@> to_bm25query(
                to_tsvector('english', 'database'),
                'docs_body_bm25'
            ) AS score
        FROM docs
        ORDER BY score
        LIMIT 40
    ) k
)
SELECT
    d.id,
    d.title,
    COALESCE(1.0 / (60 + v.rank), 0)
      + COALESCE(1.0 / (60 + k.rank), 0) AS rrf_score
FROM docs d
LEFT JOIN vector_ranked v
    ON d.id = v.id
LEFT JOIN keyword_ranked k
    ON d.id = k.id
WHERE v.id IS NOT NULL
   OR k.id IS NOT NULL
ORDER BY rrf_score DESC, d.id
LIMIT 10;

How the query works

  1. Vector retrieval: Finds the top 40 candidates by cosine distance.
  2. Keyword retrieval: Finds the top 40 candidates by BM25 relevance.
  3. Rank calculation: Assigns each candidate a position in its respective result list.
  4. Rank fusion: Adds the reciprocal-rank contributions from both lists.
  5. Final ranking: Returns the highest-scoring documents.

The LEFT JOIN and COALESCE expressions ensure that a document found by only one retrieval method still contributes to the final ranking.

The d.id tie-breaker makes result ordering deterministic for equal RRF scores, although stable pagination across changing data may still require an appropriate snapshot or cursor strategy.

Tuning tip: The candidate limit of 40 and the RRF constant of 60 are starting points, not universal defaults. Evaluate them against your dataset, relevance requirements, recall targets, and latency budget. Weighted fusion is another option when one retrieval method should contribute more strongly than the other.

7. Bringing Lakehouse Data into Lakebase with Synced Tables

You do not need to write every record directly into PostgreSQL.

Lakebase synced tables allow you to replicate a Unity Catalog Delta table into Lakebase, making lakehouse data available to operational applications and search workloads.

Available synchronization modes


ModeBehaviorChange Data Feed required Best suited for
SnapshotOne-time full copyNoInitial setup and smaller datasets
TriggeredUpdates on demand or on a scheduleYesPeriodic refreshes
ContinuousOngoing, near-real-time synchronizationYesApplications requiring frequent updates

For modes that require Change Data Feed (CDF), enable it on the source Delta table:

ALTER TABLE your_table
SET TBLPROPERTIES (
    delta.enableChangeDataFeed = true
);

Once the synced data is available in Lakebase:

  1. Create the required vector and text-search columns.
  2. Generate embeddings outside PostgreSQL, for example with Databricks Model Serving or ai_query, where supported by your workflow.
  3. Store embeddings in a VECTOR(n) column.
  4. Create the appropriate lakebase_ann and lakebase_bm25 indexes.
  5. Validate synchronization behavior and search freshness.

An important design principle: Search freshness is constrained by the freshness of the underlying synchronized data and any downstream embedding or indexing work. Select the synchronization mode based on your application’s latency requirements.

8. When Should You Use Each Search Mode?

 
Use caseRecommended approachWhy
RAG over internal documentsVector or hybridRetrieves semantically relevant passages, with hybrid search adding exact-term matching
Product and e-commerce searchHybridCombines descriptions and semantic similarity with product names and SKUs
Similar historical support ticketsVectorFinds issues with similar meaning even when wording differs
Source code, identifiers, and error codesKeywordExact terminology and identifiers matter
Recommendations based on similarityVectorFinds items with similar embedding representations

These are starting points. The best approach depends on your data, query patterns, and relevance evaluation results.

9. Trade-Offs to Consider

Lakebase Search simplifies the search architecture, but it does not eliminate the need for careful system design.

Beta status and rollout risk

The feature is in Beta, and enabling it is described as irreversible. Test it in a separate project and confirm the current feature limitations before rolling it out.

Shared compute resources

Search queries and transactional operations share the database environment. Heavy indexing or retrieval workloads can affect application latency, so benchmark realistic workloads and size your compute accordingly.

Search-engine feature differences

Lakebase Search is not necessarily a drop-in replacement for every Elasticsearch or OpenSearch capability.

Evaluate requirements such as:

  • Faceted navigation and aggregations
  • Fuzzy matching and phrase search
  • Language-specific analyzers
  • Highlighting and snippets
  • Filtering and complex ranking logic

Embedding lifecycle management

Your application is responsible for producing and maintaining embeddings. The vector dimension must match the model output and schema, and switching embedding models generally requires regenerating embeddings and rebuilding or updating the relevant indexes.

Lakebase Search versus Databricks Vector Search

If your primary requirement is a managed vector index over Delta tables, evaluate Databricks Vector Search as well.

Lakebase Search is especially worth considering when retrieval needs to live alongside operational PostgreSQL data. The right choice depends on your data architecture, query requirements, latency targets, and operational constraints.

10. Quick Reference


TaskSQL
Install vector extensionCREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
Install text extensionCREATE EXTENSION IF NOT EXISTS lakebase_text;
Define vector columnembedding VECTOR(384)
Define text-search columnbody_tsv TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', body)) STORED
Create ANN indexCREATE INDEX ON tbl USING lakebase_ann (embedding vector_cosine_ops);
Create BM25 indexCREATE INDEX idx ON tbl USING lakebase_bm25 (body_tsv);
Run vector searchSELECT * FROM tbl ORDER BY embedding <=> '[...]' LIMIT 10;
Run BM25 searchSELECT *, body_tsv <@> to_bm25query(to_tsvector('english', 'q'), 'idx') AS score FROM tbl ORDER BY score LIMIT 10;

Conclusion

Lakebase Search brings vector, keyword, and hybrid retrieval into the PostgreSQL database that already holds your operational data.

By combining lakebase_vector and lakebase_text, applications can use SQL to retrieve semantically similar content, rank keyword matches with BM25, and combine both result sets with Reciprocal Rank Fusion.

For workloads where search and transactions operate on the same data, this can reduce infrastructure complexity and eliminate some of the synchronization work associated with maintaining separate search systems.

However, Lakebase Search is still in Beta. Before adopting it for production workloads, validate its relevance, recall, latency, indexing behavior, and operational trade-offs against your own dataset.

Have you tried Lakebase Search? Share your implementation experience, performance results, and questions in the comments.

Author: Isaac Pandraju Feature status: Beta Last reviewed: October 2026

0 REPLIES 0