{"id":3093,"date":"2026-11-06T16:16:34","date_gmt":"2026-11-06T16:16:34","guid":{"rendered":""},"modified":"2026-11-06T16:16:34","modified_gmt":"2026-11-06T16:16:34","slug":"build-hybrid-search-vector-bm25-tutorial","status":"publish","type":"post","link":"https:\/\/www.kingbaseglobal.com\/blog\/tech-blog\/build-hybrid-search-vector-bm25-tutorial\/","title":{"rendered":"Build Hybrid Search_ Vector + BM25 Tutorial"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/kingbase-bbs.oss-cn-beijing.aliyuncs.com\/qywx\/blogImage\/240f9711-5c71-4864-b6fe-cbcf57958de3.webp\" alt=\"Precision tools arranged on a workshop surface for a technical tutorial\" \/><\/p>\n<h2>Architectural Prerequisites: The Multi-Model Foundation<\/h2>\n<p>Implementing a hybrid search pipeline requires reconciling the semantic recall of vector similarity with the keyword precision of lexical matching. This architecture introduces a critical consistency challenge: keeping the transactional system of record synchronized with the dual-index retrieval layer. While many enterprises deploy separate vector databases for embeddings, this approach increases infrastructure complexity and data synchronization latency.<\/p>\n<p><strong>KingbaseES<\/strong> (KES) V9 is a commercial database product that natively supports vector data types. This capability allows enterprises to store relational metadata, text content, and vector embeddings within a single commercial database system. By leveraging the native vector support in KingbaseES V9, you can simplify the stack and reduce the operational overhead associated with external vector stores. However, native support for vector data does not automatically imply a complete, out-of-the-box hybrid search engine. You must still architect the orchestration layer for keyword (BM25) indexing and score fusion.<\/p>\n<p>Before beginning implementation, ensure your environment meets these prerequisites:<\/p>\n<ul>\n<li><strong>Database Version<\/strong>: KingbaseES V9 or later, which includes native vector data type support.<\/li>\n<li><strong>Ecosystem Components<\/strong>: KFS Ultra or compatible synchronization drivers for handling vector data workflows.<\/li>\n<li><strong>Authentication<\/strong>: Configuration for national cryptographic (Guomi) authentication if operating in regulated sectors.<\/li>\n<li><strong>Performance Tools<\/strong>: Access to the KingbaseES Performance Inspection Platform for slow query management and monitoring.<\/li>\n<\/ul>\n<p>Verify that your instance is licensed as commercial software and that the vector extension is enabled. Do not assume open-source compatibility or community support mechanisms apply to this commercial product.<\/p>\n<h2>Data Modeling: Storing Embeddings and Text in KingbaseES<\/h2>\n<p>Effective hybrid search relies on a schema that efficiently stores three distinct data types: relational metadata, unstructured text for keyword indexing, and high-dimensional vectors for semantic search. KingbaseES V9 supports these models within a single system, eliminating the need for polyglot persistence for these specific data types.<\/p>\n<p>Design your table schema to accommodate vector embeddings directly. The vector data type in KingbaseES V9 supports standard floating-point arrays.<\/p>\n<h3>Step 1: Create the Document Table<\/h3>\n<p>Define a table that holds the primary key, text content, metadata, and the vector column.<\/p>\n<pre><code class=\"language-sql\">CREATE TABLE documents (\n    id SERIAL PRIMARY KEY,\n    title TEXT NOT NULL,\n    content TEXT NOT NULL,\n    category VARCHAR(50),\n    publish_date DATE,\n    embedding VECTOR(768)  -- Adjust dimension based on your model\n);\n<\/code><\/pre>\n<h3>Step 2: Insert Data with Embeddings<\/h3>\n<p>Populate the table with text and pre-generated embeddings. Ensure the embedding service generates vectors that match the dimension specified in the schema (e.g., 768 dimensions for common transformer models).<\/p>\n<pre><code class=\"language-sql\">INSERT INTO documents (title, content, category, publish_date, embedding)\nVALUES (\n    'Enterprise Data Governance',\n    'Best practices for managing data quality...',\n    'Governance',\n    '2023-10-01',\n    '[0.036124361, 0.06381883, 0.006241124, ...]' -- Truncated for brevity\n);\n<\/code><\/pre>\n<h3>Step 3: Verify Data Integrity<\/h3>\n<p>Check that the vector data is stored correctly and that text fields are accessible for keyword matching.<\/p>\n<pre><code class=\"language-sql\">SELECT id, title, length(content) as content_length\nFROM documents\nWHERE category = 'Governance'\nLIMIT 5;\n<\/code><\/pre>\n<p>This schema supports the dual-index requirement by keeping all data in one place. The <code>content<\/code> and <code>title<\/code> fields serve as the source for BM25 indexing, while the <code>embedding<\/code> field serves the vector index.<\/p>\n<h2>Indexing Strategy: Dual-Index Maintenance<\/h2>\n<p>Hybrid search requires two distinct indexing structures. The vector index supports similarity searches, while the text index supports keyword matching. Maintaining both without degrading write performance is a key architectural challenge.<\/p>\n<p>KingbaseES supports standard SQL indexing for text and relational data. For vector similarity, specific vector index types are required. Note that specific vector index creation syntax may vary by version; consult the vendor documentation for the exact command for your KingbaseES V9 build.<\/p>\n<h3>Step 1: Create Text Index for BM25<\/h3>\n<p>Create a standard index on the text fields to support keyword retrieval. For BM25 scoring, full-text search indexes are typically used.<\/p>\n<pre><code class=\"language-sql\">-- Vendor-Specific: Verify exact syntax for full-text search index creation in KingbaseES V9\nCREATE INDEX idx_doc_content_text ON documents USING gin(to_tsvector('english', content));\nCREATE INDEX idx_doc_title_text ON documents USING gin(to_tsvector('english', title));\n<\/code><\/pre>\n<h3>Step 2: Create Vector Index<\/h3>\n<p>Create an index optimized for vector distance calculations. The exact index type (e.g., HNSW, IVFFlat) depends on your latency and accuracy requirements.<\/p>\n<pre><code class=\"language-sql\">-- Vendor-Specific: Verify exact index type and operator class for your KingbaseES version\nCREATE INDEX idx_doc_embedding ON documents USING &lt;vector_index_type&gt;(embedding vector_cosine_ops);\n<\/code><\/pre>\n<h3>Step 3: Manage Index Maintenance<\/h3>\n<p>Index maintenance impacts write performance. Schedule index rebuilds or updates during low-traffic windows. Use KingbaseES performance inspection tools to monitor the impact of index operations on system load.<\/p>\n<h2>Retrieval Execution: Parallel Vector and Keyword Queries<\/h2>\n<p>To meet latency requirements, execute vector similarity and keyword searches in parallel. This approach minimizes the total retrieval time by leveraging the database&#8217;s ability to process multiple queries simultaneously.<\/p>\n<p>Since native hybrid search orchestration is not explicitly documented for KingbaseES, you must execute separate queries and merge the results in the application layer or via stored procedures.<\/p>\n<h3>Step 1: Execute Vector Similarity Query<\/h3>\n<p>Retrieve documents based on vector distance. Use cosine similarity for normalized results.<\/p>\n<pre><code class=\"language-sql\">-- Example: Find top 10 most similar documents\nSELECT id, title, embedding &lt;-&gt; '[0.01, 0.02, ...]' AS distance\nFROM documents\nORDER BY distance ASC\nLIMIT 10;\n<\/code><\/pre>\n<h3>Step 2: Execute Keyword Query<\/h3>\n<p>Retrieve documents based on keyword matching using full-text search.<\/p>\n<pre><code class=\"language-sql\">-- Vendor-Specific: Verify tokenization settings for 'english' in KingbaseES\n-- Example: Find documents matching specific terms\nSELECT id, title, ts_rank(to_tsvector('english', content), query) AS rank\nFROM documents, to_tsquery('english', 'data AND governance') query\nWHERE to_tsvector('english', content) @@ query\nORDER BY rank DESC\nLIMIT 10;\n<\/code><\/pre>\n<h3>Step 3: Combine Results<\/h3>\n<p>Merge the two result sets. Ensure you handle duplicate IDs and normalize scores before fusion. This step is critical for accurate hybrid ranking.<\/p>\n<h2>Score Fusion: Implementing Reciprocal Rank Fusion (RRF)<\/h2>\n<p>Score fusion combines the ranked lists from vector and keyword searches into a single, coherent ranking. Reciprocal Rank Fusion (RRF) is a widely used method that is robust to differences in score distributions between the two retrieval streams.<\/p>\n<p>KingbaseES does not provide a native &quot;hybrid search&quot; function that automatically applies RRF. You must implement the fusion logic using PL\/pgSQL or in the application layer.<\/p>\n<h3>RRF Formula<\/h3>\n<p>$$ RRF(d) = \\sum_{r \\in R} \\frac{1}{k + r(d)} $$<\/p>\n<p>Where:<\/p>\n<ul>\n<li>$R$ is the set of retrieval lists (vector and keyword).<\/li>\n<li>$r(d)$ is the rank of document $d$ in list $R$.<\/li>\n<li>$k$ is a constant, typically 60.<\/li>\n<\/ul>\n<h3>Step 1: Implement Fusion Logic in PL\/pgSQL<\/h3>\n<p>Create a stored procedure to merge the results. This example assumes you have two temporary tables or CTEs containing the ranked IDs from the vector and keyword queries.<\/p>\n<pre><code class=\"language-sql\">CREATE OR REPLACE FUNCTION hybrid_search_fusion(\n    p_query_embedding VECTOR(768),\n    p_keywords TEXT\n) RETURNS TABLE (id INT, title TEXT, score FLOAT) AS $$\nDECLARE\n    k CONSTANT INT := 60;\n    v_score FLOAT;\nBEGIN\n    -- This is a conceptual implementation.\n    -- In practice, you would execute the two queries separately,\n    -- collect the IDs and ranks, and then compute the RRF sum.\n\n    -- Example: Select IDs and compute RRF score\n    -- Note: Full implementation requires complex SQL logic or application-side processing.\n\n    RETURN QUERY\n    SELECT\n        d.id,\n        d.title,\n        -- Placeholder for RRF calculation logic\n        0.0 AS score\n    FROM documents d\n    WHERE d.id IN (\n        -- Subquery for vector results\n        SELECT id FROM documents ORDER BY embedding &lt;-&gt; p_query_embedding LIMIT 10\n        UNION\n        -- Subquery for keyword results\n        SELECT id FROM documents WHERE content ILIKE '%' || p_keywords || '%' LIMIT 10\n    );\nEND;\n$$ LANGUAGE plpgsql;\n<\/code><\/pre>\n<h3>Step 2: Verify Fusion Accuracy<\/h3>\n<p>Test the fusion function with known queries. Compare the results against manual relevance judgments to ensure that the RRF weighting aligns with user expectations. Adjust the constant $k$ if necessary to balance the influence of vector vs. keyword results.<\/p>\n<h2>Synchronization &amp; Freshness: Keeping the Indexes Alive<\/h2>\n<p>Data freshness is a critical constraint in hybrid search. Stale embeddings or outdated text indexes lead to poor search results. KingbaseES supports triggers and synchronization mechanisms to keep the retrieval layer in sync with the transactional system of record.<\/p>\n<h3>Step 1: Implement Triggers for Index Updates<\/h3>\n<p>Use database triggers to update the vector and text indexes when the underlying data changes. This ensures that the retrieval layer reflects the current state of the transactional data.<\/p>\n<pre><code class=\"language-sql\">CREATE OR REPLACE FUNCTION update_embedding()\nRETURNS TRIGGER AS $$\nBEGIN\n    -- Regenerate embedding if content changes\n    -- Note: Embedding generation usually happens in the application layer\n    -- or via an external service. This trigger can signal the update.\n    NEW.embedding := generate_embedding(NEW.content); -- Placeholder function\n    RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE TRIGGER trigger_update_embedding\nBEFORE UPDATE ON documents\nFOR EACH ROW\nEXECUTE FUNCTION update_embedding();\n<\/code><\/pre>\n<h3>Step 2: Leverage KFS Ultra for Vector Synchronization<\/h3>\n<p>For large-scale deployments, use KFS Ultra to handle vector data synchronization. KFS Ultra natively supports vector data types and can synchronize embedded vectors to AI\/ML applications efficiently.<\/p>\n<h3>Step 3: Monitor Index Latency<\/h3>\n<p>Use the KingbaseES Performance Inspection Platform to monitor slow queries and index update latencies. Configure crontab jobs for regular collection of performance metrics.<\/p>\n<h2>Verification &amp; Troubleshooting: Performance and Failure Modes<\/h2>\n<p>Validating hybrid search performance requires checking both accuracy and latency. Common failure modes include stale data, high latency due to complex fusion logic, and poor score fusion.<\/p>\n<h3>Verification Checklist<\/h3>\n<ol>\n<li><strong>Data Consistency<\/strong>: Verify that updated documents appear in search results within the expected latency window.<\/li>\n<li><strong>Index Freshness<\/strong>: Check that vector embeddings are regenerated and updated when text content changes.<\/li>\n<li><strong>Score Fusion Accuracy<\/strong>: Validate that RRF produces relevant results by comparing with ground-truth rankings.<\/li>\n<li><strong>Latency Monitoring<\/strong>: Ensure that parallel query execution and fusion logic do not exceed latency thresholds (e.g., &lt;200ms for search response).<\/li>\n<li><strong>Performance Inspection<\/strong>: Use KingbaseES slow query management to identify bottlenecks in vector distance calculations or text indexing.<\/li>\n<\/ol>\n<h3>Troubleshooting Common Issues<\/h3>\n<ul>\n<li><strong>Stale Results<\/strong>: If search results do not reflect recent updates, check trigger configurations and KFS Ultra synchronization status.<\/li>\n<li><strong>High Latency<\/strong>: If queries are slow, analyze the execution plan for vector and text indexes. Consider optimizing index types or reducing the number of documents scanned.<\/li>\n<li><strong>Poor Fusion<\/strong>: If results are irrelevant, review the RRF constant $k$ and the weighting of vector vs. keyword scores.<\/li>\n<\/ul>\n<h2>FAQ<\/h2>\n<h3>What are the trade-offs between Reciprocal Rank Fusion (RRF) and weighted sum for hybrid search?<\/h3>\n<p>RRF is robust to differences in score distributions and does not require normalization of scores from different retrieval streams. Weighted sum requires careful normalization and tuning of weights but can be more interpretable. RRF is often preferred for its simplicity and stability.<\/p>\n<h3>How to validate hybrid search accuracy and latency in a production-like environment?<\/h3>\n<p>Use the KingbaseES Performance Inspection Platform to monitor query execution times and resource usage. Conduct A\/B testing with real user queries to compare the relevance of hybrid search results against keyword-only or vector-only baselines.<\/p>\n<h3>What are the common failure modes in hybrid search pipelines and how to troubleshoot them?<\/h3>\n<p>Common failures include stale indexes, high latency due to complex fusion, and poor relevance. Troubleshoot by checking trigger configurations, optimizing index types, and validating the RRF implementation. Use slow query logs to identify performance bottlenecks.<\/p>\n<hr \/>\n<p><strong>\ud83d\udca1 More Resources<\/strong><\/p>\n<p>If you would like to dive deeper into KingbaseES and its application practices across various industries, we have compiled the following official resources to help you get started quickly and develop and operate with efficiency:<\/p>\n<ul>\n<li><a href=\"https:\/\/bbs.kingbase.com.cn\/\">Kingbase Community<\/a>: A one-stop interactive platform for technical exchanges, Q&amp;A, and experience sharing\u2014join forces with fellow DBAs and developers.<\/li>\n<li><a href=\"https:\/\/www.kingbaseglobal.com\/Solution-Oracle.html\">Kingbase Solutions<\/a>: One-stop full-stack database migration and cloud-native solutions, supporting smooth migration of multi-source heterogeneous data, ensuring high availability, real-time integration, and sustained high performance.<\/li>\n<li><a href=\"https:\/\/www.kingbaseglobal.com\/Customers.html\">Kingbase Case Studies<\/a>: Real-world user scenarios and implementation outcomes, showcasing KingbaseES&#8217;s outstanding capabilities in high availability, high performance, and IT adaptation.<\/li>\n<li><a href=\"https:\/\/docs.kingbase.com.cn\/en\">Kingbase Documentation<\/a>: Authoritative and comprehensive product manuals and technical guides, covering the entire lifecycle from installation and deployment to development, programming, and operations management.<\/li>\n<li><a href=\"https:\/\/www.kingbaseglobal.com\/Download.html\">Free Download<\/a>: Get the latest installation packages, drivers, tools, and patches, supporting multiple platforms and domestic chip architectures.<\/li>\n<li><a href=\"https:\/\/www.kingbaseglobal.com\/blog\/\">Digital Construction Encyclopedia<\/a>: Covers digital strategy planning, data integration, metrics management, database visualization applications, and more to empower enterprise digital transformation.<\/li>\n<\/ul>\n<p><strong>Open Source Resources:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/hgsandy\/Kingbase-docs\">GitHub &#8211; Kingbase-docs<\/a>: Kingbase documentation open-source repository\u2014Stars and contributions are welcome.<\/li>\n<li><a href=\"https:\/\/gitee.com\/hgsandy\/kingbase-docs\">Gitee &#8211; Kingbase-docs<\/a>: Domestic mirror repository for Kingbase documentation for faster access.<\/li>\n<\/ul>\n<p>Welcome to explore the resources above and begin your Kingbase journey!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Architectural Prerequisites: The Multi-Model Foundation Implementing a hybrid search pipeline requires reconciling the semantic recall of vector similarity with the keyword precision of lexical matching. This architecture introduces a critical&#8230;<\/p>\n","protected":false},"author":327,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"meta_description":"","_kingbase_seo_description":"","footnotes":""},"categories":[],"tags":[],"class_list":["post-3093","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/posts\/3093","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/users\/327"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/comments?post=3093"}],"version-history":[{"count":0,"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/posts\/3093\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/media?parent=3093"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/categories?post=3093"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kingbaseglobal.com\/blog\/wp-json\/wp\/v2\/tags?post=3093"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}