> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch28-memory-system/28.3-hybrid-search.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 28.3 Hybrid Search (BM25 + Vector)

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~330k tokens, Output \~7k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Vector search excels at capturing **semantic relevance**—the vectors for "TypeScript configuration" and "TS project setup" are close together, even though they share no keywords. But vector search also has blind spots: when the user searches for an exact function name `calculateTotal`, traditional keyword matching is actually more precise. OpenClaw's solution is **hybrid search**—merging results from BM25 full-text search and vector search, balancing exact matching and semantic understanding.

***

## 28.3.1 BM25 Full-Text Search Principles

### What is BM25?

> **Sidebar**: BM25 (Best Matching 25) is one of the most classic ranking algorithms in information retrieval, proposed by Stephen Robertson and others in 1994. It's an improved version of TF-IDF (Term Frequency-Inverse Document Frequency), with the core idea: the higher a term's frequency in a document (TF), and the lower its frequency across all documents (IDF), the more important that term is to the document. BM25 improves upon TF-IDF with two enhancements: (1) term frequency saturation—after a certain point, increased frequency doesn't contribute linearly; (2) document length normalization—longer documents don't gain advantage just from having more terms. The formula is:
>
> $$\text{BM25}(q, d) = \sum\_{t \in q} \text{IDF}(t) \cdot \frac{f(t, d) \cdot (k\_1 + 1)}{f(t, d) + k\_1 \cdot (1 - b + b \cdot \frac{|d|}{\text{avgdl}})}$$
>
> Where $f(t, d)$ is the frequency of term $t$ in document $d$, $|d|$ is document length, $\text{avgdl}$ is average document length, and $k\_1$ and $b$ are tunable parameters.

OpenClaw doesn't need to implement BM25 itself—SQLite's FTS5 engine has BM25 ranking built-in. What OpenClaw does is: (1) insert text chunks into the FTS5 virtual table, (2) construct appropriate MATCH queries, (3) convert BM25 ranking to normalized scores that can be merged with vector scores.

### FTS Query Construction

User natural language queries need to be converted to MATCH expressions that FTS5 understands. `buildFtsQuery` handles this conversion:

```typescript
// src/memory/hybrid.ts

export function buildFtsQuery(raw: string): string | null {
  const tokens = raw
    .match(/[A-Za-z0-9_]+/g)           // Extract all alphanumeric terms
    ?.map(t => t.trim())
    .filter(Boolean) ?? [];
  if (tokens.length === 0) return null;  // No valid terms, skip search
  const quoted = tokens.map(t => `"${t.replaceAll('"', '')}"`);
  return quoted.join(" AND ");           // All terms must appear
}
```

Conversion examples:

| User Input                 | FTS Query                             | Meaning                                               |
| -------------------------- | ------------------------------------- | ----------------------------------------------------- |
| `TypeScript configuration` | `"TypeScript" AND "configuration"`    | — Note: Chinese filtered, only `"TypeScript"` remains |
| `calculate total price`    | `"calculate" AND "total" AND "price"` | All three terms must appear                           |
| `API_KEY setup`            | `"API_KEY" AND "setup"`               | Underscore is part of term                            |
| `你好世界`                     | `null`                                | All Chinese, no valid tokens                          |

Note an important limitation: `buildFtsQuery` uses `[A-Za-z0-9_]+` regex to extract tokens, meaning **pure Chinese queries are filtered to empty** and fall back to pure vector search. This is a reasonable trade-off—FTS5's default tokenizer has limited Chinese support, while vector search naturally supports multiple languages.

### Keyword Search Implementation

`searchKeyword` executes the actual FTS5 query:

```typescript
// src/memory/manager-search.ts (simplified)

export async function searchKeyword(params: {
  db: DatabaseSync;
  ftsTable: string;          // "chunks_fts"
  providerModel: string;
  query: string;
  limit: number;
  snippetMaxChars: number;
  sourceFilter: { sql: string; params: string[] };
  buildFtsQuery: (raw: string) => string | null;
  bm25RankToScore: (rank: number) => number;
}): Promise<Array<SearchRowResult & { textScore: number }>> {
  const ftsQuery = params.buildFtsQuery(params.query);
  if (!ftsQuery) return [];  // No valid query terms

  const rows = params.db.prepare(
    `SELECT id, path, source, start_line, end_line, text,
            bm25(${params.ftsTable}) AS rank
       FROM ${params.ftsTable}
      WHERE ${params.ftsTable} MATCH ?
        AND model = ?
      ORDER BY rank ASC
      LIMIT ?`
  ).all(ftsQuery, params.providerModel, params.limit);

  return rows.map(row => ({
    id: row.id,
    path: row.path,
    startLine: row.start_line,
    endLine: row.end_line,
    score: params.bm25RankToScore(row.rank),
    textScore: params.bm25RankToScore(row.rank),
    snippet: truncateUtf16Safe(row.text, params.snippetMaxChars),
    source: row.source,
  }));
}
```

Key points:

1. **`bm25()` function**: FTS5's built-in ranking function, returns a negative number (smaller is more relevant). SQLite documentation calls it "rank", with range $(-\infty, 0]$.
2. **`ORDER BY rank ASC`**: Because smaller rank is better, sort ascending.
3. **`model` filter**: Ensure only searching chunks for the current embedding model, avoiding cross-model confusion.

### BM25 Score Normalization

FTS5's `bm25()` returns a negative rank, which needs to be converted to the $\[0, 1]$ interval to merge with vector search's cosine similarity:

```typescript
// src/memory/hybrid.ts

export function bm25RankToScore(rank: number): number {
  const normalized = Number.isFinite(rank) ? Math.max(0, rank) : 999;
  return 1 / (1 + normalized);
}
```

Wait—`Math.max(0, rank)` on a negative rank returns 0, and `1 / (1 + 0) = 1`? Actually, SQLite FTS5's `bm25()` return value in OpenClaw's usage scenario, after being processed by `ORDER BY rank ASC`, is **non-negative** in most implementations (depends on SQLite version and configuration). The conversion function uses reciprocal mapping $s = \frac{1}{1 + r}$:

| rank | score   | Meaning                        |
| ---- | ------- | ------------------------------ |
| 0    | 1.0     | Most relevant                  |
| 1    | 0.5     |                                |
| 4    | 0.2     |                                |
| 9    | 0.1     |                                |
| 999  | ≈ 0.001 | Nearly irrelevant (or anomaly) |

This mapping is **monotonically decreasing** and naturally compresses scores to the $(0, 1]$ interval, compatible with cosine similarity's range $\[-1, 1]$ (typically $\[0, 1]$ in practice).

***

## 28.3.2 Hybrid Retrieval Implementation

### Search Entry Point

`MemoryIndexManager.search()` is the entry point for hybrid search. It orchestrates three phases: keyword search, vector search, result merging.

```typescript
// src/memory/manager.ts (simplified)

async search(query: string, opts?: { maxResults?: number; minScore?: number }) {
  const minScore = opts?.minScore ?? this.settings.query.minScore;
  const maxResults = opts?.maxResults ?? this.settings.query.maxResults;
  const hybrid = this.settings.query.hybrid;

  // Candidate count = final results × candidate multiplier (max 200)
  const candidates = Math.min(200,
    Math.max(1, Math.floor(maxResults * hybrid.candidateMultiplier))
  );

  // Phase 1: Keyword search (BM25)
  const keywordResults = hybrid.enabled
    ? await this.searchKeyword(query, candidates).catch(() => [])
    : [];

  // Phase 2: Vector search
  const queryVec = await this.embedQueryWithTimeout(query);
  const hasVector = queryVec.some(v => v !== 0);
  const vectorResults = hasVector
    ? await this.searchVector(queryVec, candidates).catch(() => [])
    : [];

  // Phase 3: Merge or return directly
  if (!hybrid.enabled) {
    return vectorResults
      .filter(e => e.score >= minScore)
      .slice(0, maxResults);
  }

  const merged = this.mergeHybridResults({
    vector: vectorResults,
    keyword: keywordResults,
    vectorWeight: hybrid.vectorWeight,    // Default 0.7
    textWeight: hybrid.textWeight,        // Default 0.3
  });

  return merged
    .filter(e => e.score >= minScore)
    .slice(0, maxResults);
}
```

Key design decisions:

1. **Candidate multiplier**: If the user only needs 10 results, the system requests `10 × multiplier` candidates from each search channel (default multiplier = 3, i.e., 30 candidates). More candidates mean more accurate Top-K after merging, at the cost of slightly more search volume.
2. **Error isolation**: Both search channels are wrapped with `.catch(() => [])`—keyword search failure doesn't affect vector search, and vice versa.
3. **Zero vector detection**: If the embedding API returns an all-zero vector (usually indicating embedding failure), skip vector search and use only keyword results.

Complete search flow as a sequence diagram:

```
User query "TypeScript project configuration"
          │
          ▼
   ┌──────────────────┐
   │ search()         │
   └──────┬───────────┘
          │
     ┌────┴────┐
     ▼         ▼
Keyword channel  Vector channel
     │         │
     │  buildFtsQuery()
     │  → "TypeScript"
     │         │
     │  embedQuery()
     │  → [0.023, -0.017, ...]
     │         │
     ▼         ▼
FTS5 MATCH  vec_distance_cosine
bm25() rank  cosine distance
     │         │
     ▼         ▼
bm25RankToScore  1 - distance
     │         │
     └────┬────┘
          ▼
   mergeHybridResults()
   ┌──────────────────────────┐
   │ vectorWeight × vecScore  │
   │ + textWeight × textScore │
   └──────────┬───────────────┘
              ▼
       Sort + Filter + Truncate
              │
              ▼
       Return MemorySearchResult[]
```

***

## 28.3.3 Score Merging Strategy: Weighted Linear Combination

### Merging Algorithm

`mergeHybridResults` is the core of hybrid search—merging results from both sources by ID and computing weighted scores:

```typescript
// src/memory/hybrid.ts

export function mergeHybridResults(params: {
  vector: HybridVectorResult[];    // { id, vectorScore, ... }
  keyword: HybridKeywordResult[];  // { id, textScore, ... }
  vectorWeight: number;            // Default 0.7
  textWeight: number;              // Default 0.3
}): Array<{ path, startLine, endLine, score, snippet, source }> {
  const byId = new Map();

  // 1. Collect vector search results first
  for (const r of params.vector) {
    byId.set(r.id, {
      ...r,
      vectorScore: r.vectorScore,
      textScore: 0,               // Default text score is 0
    });
  }

  // 2. Merge keyword search results
  for (const r of params.keyword) {
    const existing = byId.get(r.id);
    if (existing) {
      existing.textScore = r.textScore;  // Same chunk hit by both
    } else {
      byId.set(r.id, {                   // Only hit by keyword
        ...r,
        vectorScore: 0,
        textScore: r.textScore,
      });
    }
  }

  // 3. Compute weighted scores and sort
  const merged = Array.from(byId.values()).map(entry => ({
    ...entry,
    score: params.vectorWeight * entry.vectorScore
         + params.textWeight  * entry.textScore,
  }));

  return merged.toSorted((a, b) => b.score - a.score);
}
```

The merging formula is very intuitive:

$$\text{score}*{\text{final}} = w\_v \times s*{\text{vector}} + w\_t \times s\_{\text{text}}$$

Where default $w\_v = 0.7$, $w\_t = 0.3$.

### Three Hit Scenarios

A text chunk can be in three states during merging:

| Scenario         | Vector Score | Text Score | Final Score                                 |
| ---------------- | ------------ | ---------- | ------------------------------------------- |
| **Double hit**   | 0.85         | 0.72       | $0.7 \times 0.85 + 0.3 \times 0.72 = 0.811$ |
| **Vector only**  | 0.85         | 0          | $0.7 \times 0.85 = 0.595$                   |
| **Keyword only** | 0            | 0.72       | $0.3 \times 0.72 = 0.216$                   |

Chunks with double hits get the highest scores—this is the value of hybrid search. A result that is both semantically relevant and contains exact keywords is almost certainly what the user wants.

### Weight Meaning

The default 7:3 weight favors vector search, reflecting a design judgment: for AI Agent memory retrieval scenarios, **semantic understanding is more important than exact matching**. When a user searches "the database solution we discussed before", vector search can find memory chunks containing "PostgreSQL vs MongoDB comparison", while keyword search might find nothing (no shared vocabulary).

But the 30% weight for keyword search is also important—it provides critical supplementation in these scenarios:

* **Exact name search**: Function names, variable names, project names
* **Error message search**: Searching for specific error text
* **Version number search**: Searching for exact strings like "v2.3.1"
* **Mixed Chinese-English queries**: English keywords matched precisely by BM25, Chinese semantics supplemented by vectors

### Configuration Tunable

Weights and other hybrid search parameters can be overridden through configuration:

```typescript
// src/agents/memory-search.ts (default values)

const DEFAULT_HYBRID_VECTOR_WEIGHT = 0.7;
const DEFAULT_HYBRID_TEXT_WEIGHT = 0.3;
const DEFAULT_HYBRID_CANDIDATE_MULTIPLIER = 3;
const DEFAULT_HYBRID_ENABLED = true;
```

Users can adjust in `settings.json`:

```json
{
  "agents": {
    "defaults": {
      "memorySearch": {
        "hybrid": {
          "enabled": true,
          "vectorWeight": 0.5,
          "textWeight": 0.5,
          "candidateMultiplier": 5
        }
      }
    }
  }
}
```

Setting `vectorWeight: 0, textWeight: 1` completely disables vector search, using only BM25; conversely, setting `enabled: false` completely disables hybrid search, using only vectors.

***

## 28.3.4 From Theory to Practice: A Complete Search

Let's trace a complete hybrid search to understand how data flows through each layer.

**Scenario**: User asks Agent "What database did we decide to use?"

**Step 1**: Agent calls `memory_search` tool with query "What database did we decide to use?"

**Step 2**: `search()` method starts two parallel channels

* **Keyword channel**: `buildFtsQuery("What database did we decide to use?")` → `"database"` (other words filtered) → Returns results with "database"
* **Vector channel**: Embedding API converts query to 1536-dimensional vector → sqlite-vec executes cosine distance search → Returns Top-30 candidates

**Step 3**: Merge results, chunks with both keyword and vector hits score highest

**Step 4**: Filter `score >= minScore`, return Top-10 to Agent

Now a different scenario: user searches "PostgreSQL migration plan"

* **Keyword channel**: `buildFtsQuery(...)` → `"PostgreSQL" AND "migration" AND "plan"` → BM25 returns chunks containing all three terms
* **Vector channel**: Vector search returns semantically related chunks (might include "database migration plan", "switching from MongoDB", etc.)
* **Merge**: Chunks hit by both get highest scores, e.g., a chunk titled "PostgreSQL migration plan — 2026.01.10"

This example nicely demonstrates hybrid search's complementarity: keyword search precisely targets chunks containing "PostgreSQL", while vector search supplements semantically related but differently-worded results.

***

## Summary of This Section

1. **BM25 full-text search** is implemented via SQLite FTS5, `buildFtsQuery` converts user input to AND-connected quoted term queries, `bm25RankToScore` converts ranking to normalized scores in $(0, 1]$ interval.
2. **Hybrid search entry point** `search()` starts both keyword and vector channels simultaneously, each with independent fault tolerance (`.catch(() => [])`), ensuring merge quality through candidate multiplier (default 3x).
3. **Weighted linear combination** is the core merging strategy: $\text{score} = 0.7 \times s\_{\text{vec}} + 0.3 \times s\_{\text{text}}$. Double-hit chunks get highest scores, ensuring results that are both semantically relevant and contain exact keywords rank first.
4. **Special handling for Chinese queries**: Since FTS5's tokenizer has limited Chinese support, pure Chinese queries naturally degrade to pure vector search, a reasonable design trade-off.
5. **All parameters configurable**: Weight ratios, candidate multiplier, whether to enable hybrid search, all adjustable via `settings.json` to suit different use cases.
