# Build hybrid search for your docs

> Search Knotkit’s module docs by API name or by describing what you need.

`compressedSparseRowGraph`

Looking for [knotkit/graph](/modules/graph/)

## Keyword

BM25

1. [graph](/modules/graph/)

## Semantic

Embedding similarity

1. [graph](/modules/graph/)
2. [trie](/modules/trie/)
3. [prng](/modules/prng/)
4. [scalar-sketch](/modules/scalar-sketch/)
5. [sampling](/modules/sampling/)

## Hybrid

Rank fusion

1. [graph](/modules/graph/)
2. [trie](/modules/trie/)
3. [prng](/modules/prng/)
4. [scalar-sketch](/modules/scalar-sketch/)
5. [sampling](/modules/sampling/)

Showing up to 5 results from 32 module summaries.

## Try your own query

Type a task you’re working on or a function name, then press **Search**. Compare the results under **Keyword**, **Semantic**, and **Hybrid**. Keyword results appear while a worker loads the embedding model for the first custom query. The worker encodes your text in your browser and reuses the model for later searches.

Use **API name** to find `compressedSparseRowGraph`. Try **Customer quotas** to find the rate-limit module by meaning. **Sample a stream** shows a query where both methods put the same module first.

## Run the TypeScript

Knotkit builds the keyword index once. NumPyTS multiplies the document matrix by the query vector to score every document. With unit-length embeddings, the dot product is cosine similarity. [Reciprocal rank fusion](https://cormack.uwaterloo.ca/cormack/cormacksigir09-rrf.pdf) combines the first ten hits from each method. A document gets more credit for appearing higher in either list.

Use [Knotkit from source](/getting-started/#install-from-source) and install `numpy-ts@1.8.0`. Pass documents and query vectors produced by the same embedding model.

The demo bundles [BGE-small embeddings](https://huggingface.co/BAAI/bge-small-en-v1.5) for the module summaries and example queries. The first custom search downloads the 34 MB model and the WebAssembly runtime. The fixture generator at `apps/docs/scripts/embed-hybrid-search.py` records the model revision and reads the module summaries and API names from the capability catalog.

```ts
import { termIndex } from 'knotkit/term-index'
import { array, matmul } from 'numpy-ts/core'

interface SearchDocument {
  readonly text: string
  readonly embedding: ArrayLike<number>
}

const shortlistSize = 10
const rankOffset = 60
const stopWords = new Set(
  'a an and are as at be by can do each for from give how i in into is it of on or please that the to with you'.split(
    ' ',
  ),
)
const terms = (text: string): string[] =>
  (text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).filter((term) => !stopWords.has(term))

export function hybridDocSearch(documents: readonly SearchDocument[]) {
  const index = termIndex(documents, ({ text }) => terms(text))
  const matrix = array(
    documents.map(({ embedding }) => Array.from(embedding)),
    'float64',
  )

  return (query: string, embedding?: ArrayLike<number>) => {
    const keyword = index.search(terms(query), { limit: shortlistSize }).map(({ id }) => id)

    if (embedding === undefined) {
      return { keyword, semantic: [], hybrid: [] }
    }

    const queryVector = array(Float64Array.from(embedding), 'float64')
    const similarities = new Float64Array(matmul(matrix, queryVector).tobytes())
    const semantic = Array.from(similarities.keys())
      .toSorted((a, b) => similarities[b] - similarities[a] || a - b)
      .slice(0, shortlistSize)
    const scores = new Map<number, number>()

    for (const ranking of [keyword, semantic]) {
      for (const [rank, id] of ranking.entries()) {
        scores.set(id, (scores.get(id) ?? 0) + 1 / (rankOffset + rank + 1))
      }
    }

    const hybrid = Array.from(scores.entries())
      .toSorted(([a, left], [b, right]) => right - left || a - b)
      .map(([id]) => id)

    return { keyword, semantic, hybrid }
  }
}
```

**Modules:** [`knotkit/term-index`](/modules/term-index/) · [API reference](/reference/knotkit/term-index/)
